I have a binary represenation of a number and want to convert it to long (I have Java 8)
public class TestLongs {
public static void main(String[] args){
String a = Long.toBinaryString(Long.parseLong("-1")); // 1111111111111111111111111111111111111111111111111111111111111111
System.out.println(a);
System.out.println(Long.parseLong(a, 2));// ??? but Long.parseUnsignedLong(a, 2) works
}
}
This code results in Exception in thread "main" java.lang.NumberFormatException: For input string: "1111111111111111111111111111111111111111111111111111111111111111"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
1111111111111111111111111111111111111111111111111111111111111111
at java.lang.Long.parseLong(Long.java:592)
What is wrong here? Why Long.parseLong(a, 2) doesn't work?
Long.parseLong()
doesn't treat the first '1' character as a sign bit, so the number is parsed as 2^64-1, which is too large for long
. Long.parseLong()
expects input String
s that represent negative numbers to start with '-'.
In order for Long.parseLong(str,2)
To return -1
, you should pass to it a String
that start with '-' and ends with the binary representation of 1
- i.e. Long.parseLong("-1",2)
.
Eran is right, and the answer to your question is:
System.out.println(new BigInteger(a, 2).longValue());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With