So I have this binary string (32 chars corresponding to 32 bits):
String s = "11111111110000011101110111011000";
When I try to convert it to a number, it throws a NumberFormatException:
Integer.parseInt(s,2);
Could not figure out why. Any idea? The strange thing is if I replace the first bit in the string from the left (1) with a zero bit (0), then it works. The first bit is only for indicating the sign of the number, so I should not make any overflow of 4 bytes in here, right?
=================
UPDATED QUESTION : Thanks to everyone for the answers. I got it now; basically the parseInt() method CANNOT handle the sign bit and it assumes that the sign bit just represents the value as any other bit. So now the question is how to I convert such binary string to a signed INTEGER number? I know some of you suggested I use long, but in my situation I just need it to be an int (long to explain, but you can assume that).
The number that you're trying to parse is bigger than 2^31-1
( max integer ), use Long instead:
String s = "11111111110000011101110111011000";
System.out.println(Long.parseLong(s, 2)); // 4,290,895,320
If you want to see what's the maximum value of an Integer you can do:
System.out.println(Integer.MAX_VALUE); // 2,147,483,647
Responding your UPDATE section, if you don't mind loosing information (which happens when you convert long to int) you can do:
String s = "11111111110000011101110111011000";
long l = Long.parseLong(s,2);
int i = (int)l;
System.out.println(i); // -4071976
As other people already mentioned, this binary string does not fit the 32-bit singed int. However since Java 8 you can parse it as unsigned int, which works perfectly!
String s = "11111111110000011101110111011000";
System.out.println(Integer.parseUnsignedInt(s, 2)); // -4071976
There are other useful unsigned math methods added in Java 8 as well.
You are trying to parse a 32-bit number into an Integer
, which can only have 31 bits and a sign. parseInt
can't handle the sign bit; you need to give the sign as +
or -
(or nothing). Your number should be (if I haven't screwed up my conversion) -4071976
, which can be parsed if you give it to parseInt
as -1111100010001000101000
, but not as 11111111110000011101110111011000
.
You are telling that you are trying to parse binay String
String s = "11111111110000011101110111011000";
But this value is out of Java integer range:
Integer is 32 bit and for Java, the range is -2,147,483,648 to 2,147,483,647. But your input has the value which is out of the range. So you are getting the exception.
But long is having 64 bit and the range is –9,223,372,036,854,775,808 to 9 ,223,372,036,854,775,807. So you can use the below:
String s = "11111111110000011101110111011000";
Long.parseLong(s,2);//4290895320
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.