You are trying to parse a 64-bit unsigned (long) integer as a 64-bit signed (long) integer.
Java's long
is not unsigned. You will only be able to store a positive number up to 63 bits. The max value for a long
is 9,223,372,036,854,775,807
or 2^(63)
.
The most-significant bit (left-most) is the signed bit.
- If it's a 64-bit string that begins with a 1, it's negative.
- If it's less than 64 bits, it's positive and the leading 0 will not be displayed.
Note: Any leading zeroes will not be displayed.
import java.math.BigInteger;
public class NumberUtils {
static final String MIN_SIGNED_LONG_BINARY = Long.toBinaryString(Long.MIN_VALUE);
static final String MAX_SIGNED_LONG_BINARY =
padStart(Long.toBinaryString(Long.MAX_VALUE), 64, "0");
public static void main(String[] args) {
parseBinary("1111000000000111000000000001000000000010010000000000000000000000");
parseBinary("1100000001000000010000000100000000001110000000010000010000000000");
}
private static void parseBinary(String str) {
BigInteger bigInt = new BigInteger(str, 2);
System.out.println(bigInt.longValue());
try {
Long.parseLong(str, 2);
} catch (NumberFormatException e) {
System.out.printf(
"Error:%n* Min: %s (%d bits)%n* Val: %s (%d bits)%n* Max: %s (%d bits)%n",
MIN_SIGNED_LONG_BINARY,
MIN_SIGNED_LONG_BINARY.length(),
str,
str.length(),
MAX_SIGNED_LONG_BINARY,
MAX_SIGNED_LONG_BINARY.length());
}
}
public static String padStart(String inputString, int targetLength, String padString) {
if (inputString.length() >= targetLength) return inputString;
StringBuilder sb = new StringBuilder();
while (sb.length() < targetLength - inputString.length()) {
sb.append(padString);
}
return sb.append(inputString).toString();
}
}
Output
-1150951111012646912
Error:
* Min: 1000000000000000000000000000000000000000000000000000000000000000 (64 bits)
* Val: 1111000000000111000000000001000000000010010000000000000000000000 (64 bits)
* Max: 0111111111111111111111111111111111111111111111111111111111111111 (64 bits)
-4593600976060873728
Error:
* Min: 1000000000000000000000000000000000000000000000000000000000000000 (64 bits)
* Val: 1100000001000000010000000100000000001110000000010000010000000000 (64 bits)
* Max: 0111111111111111111111111111111111111111111111111111111111111111 (64 bits)