NumberFormatException in InputString - java

Please help me solve this exception:-
String strBinary="100000000000000001000000000000000000000000000000000000000000000000000000";
System.out.println("length is " + strBinary.length());
long intParse=Long.parseLong(strBinary, 2);
System.out.println("int parsed is " + intParse);
String hexString=Long.toHexString(intParse);
System.out.println(hexString);
Output is 72 along with NumberFormatException while parsing using Long.parseLong..
But till yesterday it was running absolutely fine for this input also..
does it have anything to do with the length...
I am actuallly trying to convert String into its equivalent Hex value.
Please help....

A long can hold 64 bit of data. The biggest value a long can represent is 9223372036854775807 (or 263-1). The string you try to parse is a lot larger than that.
You might be able to go somewhere by using the BigInteger class, which can handle arbitrary-sized integer values (effectively restricted by memory, of course).

Long is small for your purpose. You might want to use BigInteger object like this
String strBinary="100000000000000001000000000000000000000000000000000000000000000000000000";
BigInteger bigInteger = new BigInteger(strBinary, 2);
System.out.println(bigInteger.longValue()); //This would give you the long value
System.out.println(bigInteger.toString(16)); //This would give you the hex string

Related

Convert hexadecimal string to hexadecimal integer in java

I have hexadecimal String eg. "0x103E" , I want to convert it into integer.
Means String no = "0x103E";
to int hexNo = 0x103E;
I tried Integer.parseInt("0x103E",16); but it gives number format exception.
How do I achieve this ?
You just need to leave out the "0x" part (since it's not actually part of the number).
You also need to make sure that the number you are parsing actually fits into an integer which is 4 bytes long in Java, so it needs to be shorter than 8 digits as a hex number.
No need to remove the "0x" prefix; just use Integer.decode instead of Integer.parseInt:
int x = Integer.decode("0x103E");
System.out.printf("%X%n", x);

Problems parsing String to long - what am I doing wrong?

Here is the code I am working with in a main method:
String numbers = "12345678900";
long upc = Integer.parseInt(numbers);
System.out.println(upc);
gives me:
Exception in thread "main" java.lang.NumberFormatException: For input string: "12345678900"
at java.lang.NumberFormatException.forInputString...
at java.lang.Integer.parseInt....
at java.lang.Integer.parseInt...
at testRun.main...
I cannot use a double, they need to be stored as values without a decimal. I am trying to get the string of numbers from a string into a variable that holds numbers (no decimals)
To parse a long, use Long.parseLong, not Integer.parseInt. That way, you get access to the full range of long values (whereas with parseInt, you only get the rather more restricted range of int values).
Use Long.parseLong()
String numbers = "12345678900";
long upc = Long.parseLong(numbers);
System.out.println(upc);
use
String numbers = "12345678900";
long upc = Long.parseLong(numbers);
System.out.println(upc);
The number you are passing is outside the range of integer which is from -2,147,483,648 to 2,147,483,647.
Try using the static function parseLong
Your number is enough long to not fit in Integer. So, you can't cast in integer. You can cast it in Long by calling Long.parseLong(number).
Use
long upc = Long.parseLong(numbers);

java convert to int

I am trying to convert to int like this, but I am getting an exception.
String strHexNumber = "0x1";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
It would be a great help if someone can fix it.
Thanks.
That's because the 0x prefix is not allowed. It's only a Java language thing.
String strHexNumber = "F777";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println(decimalNumber);
If you want to parse strings with leading 0x then use the .decode methods available on Integer, Long etc.
int value = Integer.decode("0x12AF");
System.out.println(value);
Sure - you need to get rid of the "0x" part if you want to use parseInt:
int parsed = Integer.parseInt("100", 16);
System.out.println(parsed); // 256
If you know your value will start with "0x" you can just use:
String prefixStripped = hexNumber.substring(2);
Otherwise, just test for it:
number = number.startsWith("0x") ? number.substring(2) : number;
Note that you should think about how negative numbers will be represented too.
EDIT: Adam's solution using decode will certainly work, but if you already know the radix then IMO it's clearer to state it explicitly than to have it inferred - particularly if it would surprise people for "035" to be treated as octal, for example. Each method is appropriate at different times, of course, so it's worth knowing about both. Pick whichever one handles your particular situation most cleanly and clearly.
Integer.parseInt can only parse strings that are formatted to look just like an int. So you can parse "0" or "12343" or "-56" but not "0x1".
You need to strip off the 0x from the front of the string before you ask the Integer class to parse it. The parseInt method expects the string passed in to be only numbers/letters of the specified radix.
try using this code here:-
import java.io.*;
import java.lang.*;
public class HexaToInteger{
public static void main(String[] args) throws IOException{
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexadecimal value:!");
String s = read.readLine();
int i = Integer.valueOf(s, 16).intValue();
System.out.println("Integer:=" + i);
}
}
Yeah, Integer is still expecting some kind of String of numbers. that x is really going to mess things up.
Depending on the size of the hex, you may need to use a BigInteger (you can probably skip the "L" check and trim in yours ;-) ):
// Convert HEX to decimal
if (category.startsWith("0X") && category.endsWith("L")) {
category = new BigInteger(category.substring(2, category.length() - 1), 16).toString();
} else if (category.startsWith("0X")) {
category = new BigInteger(category.substring(2, category.length()), 16).toString();
}

C /C++ long long to Java long

I have a file on disk which I'm reading which has been written by c/c++ code. I know I have two 64-bit unsigned integers to read, but Java doesn't support unsigned integers, so the value I get when I do DataInputStream.readLong() is incorrect. (Ignore byte-order for now I'm actually using a derivative of DIS called LEDataInputStream which I downloaded from the web)
A lot of posts on here talk about using BigInteger but the javadoc for reading a bytearray only talks about loading a bytearray respresentation, and the questions seem centered on the fact that some people are going outside the positive bounds of the java long type, which I will be nowhere near with the data I'm reading.
I have a MATLab/Octave script which reads these long long values as two 32-bit integers each, then does some multiplying and adding to get the answer it wants too.
I suppose the question is - how do i read a 64-bit unsigned integer either using BigInteger, or using [LE]DataInputStream.XXX?
Thanks in advance
I would suggest using a ByteBuffer and then using code such as this to get what you want.
You can use a long as a 64-bit value to store unsigned data. Here is a module showing that most Unsigned operations can be performed using the standard long type. It really depends on what you want to do with the value as whether this is problem or not.
EDIT: A common approach to handling unsigned numbers is to widen the data type. This simpler in many cases but not a requirement (and for long using BigInteger doesn't make things any simpler IMHO)
EDIT2: What is wrong with the following code?
long max_unsigned = 0xFFFFFFFFFFFFFFFFl;
long min_unsigned = 0;
System.out.println(Unsigned.asString(max_unsigned) + " > "
+ Unsigned.asString(min_unsigned) + " is "
+ Unsigned.gt(max_unsigned, min_unsigned));
prints
18446744073709551615 > 0 is true
first you check out this question
Also see this
Now use of BigInteger class
// Get a byte array
byte[] bytes = new byte[]{(byte)0x12, (byte)0x0F, (byte)0xF0};
// Create a BigInteger using the byte array
BigInteger bi = new BigInteger(bytes);
// Format to binary
String s = bi.toString(2); // 100100000111111110000
// Format to octal
s = bi.toString(8); // 4407760
// Format to decimal
s = bi.toString(); // 1183728
// Format to hexadecimal
s = bi.toString(16); // 120ff0
if (s.length() % 2 != 0) {
// Pad with 0
s = "0"+s;
}
// Parse binary string
bi = new BigInteger("100100000111111110000", 2);
// Parse octal string
bi = new BigInteger("4407760", 8);
// Parse decimal string
bi = new BigInteger("1183728");
// Parse hexadecimal string
bi = new BigInteger("120ff0", 16);
// Get byte array
bytes = bi.toByteArray();

Is J2ME's Integer.parseInt() broken?

While writing a game for J2ME we ran into an issue using java.lang.Integer.parseInt()
We have several constant values defined as hex values, for example:
CHARACTER_RED = 0xFFAAA005;
During the game the value is serialized and is received through a network connection, coming in as a string representation of the hex value. In order to parse it back to an int we unsuccesfully tried the following:
// Response contains the value "ffAAA005" for "characterId"
string hexValue = response.get("characterId");
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
Then I ran some tests and tried this:
string hexValue = Integer.toHexString(0xFFAAA005);
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
This is the exception from the actual code:
java.lang.NumberFormatException: ffaaa005
at java.lang.Integer.parseInt(Integer.java:462)
at net.triadgames.acertijo.GameMIDlet.startMIDlet(GameMIDlet.java:109)
This I must admit, baffled me. Looking at the parseInt code the NumberFormatException seems to be thrown when the number being parsed "crosses" the "negative/positive boundary" (perhaps someone can edit in the right jargon for this?).
Is this the expected behavior for the Integer.parseInt function? In the end I had to write my own hex string parsing function, and I was quite displeased with the provided implementation.
In other words, was my expectation of having Integer.parseInt() work on the hex string representation of an integer misguided?
EDIT: In my initial posting I wrote 0xFFFAAA005 instead of 0xFFAAA005. I've since corrected that mistake.
The String you are parsing is too large to fit in an int. In Java, an int is a signed, 32-bit data type. Your string requires at least 36 bits.
Your (positive) value is still too large to fit in a signed 32-bit int.
Do realize that your input (4289372165) overflows the maximum size of an int (2147483647)?
Try parsing the value as a long and trim the leading "0x" off the string before you parse it:
public class Program {
public static void main(String[] args) {
String input = "0xFFFAAA005";
long value = Long.parseLong(input.substring(2), 16);
System.out.print(value);
}
}
I'm not a java dev, but I'd guess parseInt only works with integers. 0xFFFAAA005 has 9 hex digits, so it's a long, not an int. My guess is it's complaining because you asked it to parse a number that's bigger than it's result data type.
Your number seems to be too large to fit in an int, try using Long.parseLong() instead.
Also, the string doesn't seem to get parsed if you have 0x in your string, so try to cut that off.

Categories