I want to convert a 64-width binary string to long, there is a static method:
Long.parseLong(String s, int radix)
to do this, but it isn't suitable for my case.
The problem is my binary string is a machine-style long int.
For example:
1111111111111111111111111111111111111111111111111111111110000101
represents -123
, but this method recognize it as a huge positive number, this troubles me, how could I solve this problem?
Must I write a function that does the complement?
You can use BigInteger
public static void main(String... args) {
String s = "1111111111111111111111111111111111111111111111111111111110000101";
long l = parseLong(s, 2);
System.out.println(s +" => " + l);
String s2 = s.substring(1);
long l2 = parseLong(s2, 2);
System.out.println(s2 +" => " + l2);
}
private static long parseLong(String s, int base) {
return new BigInteger(s, base).longValue();
}
prints
1111111111111111111111111111111111111111111111111111111110000101 => -123
111111111111111111111111111111111111111111111111111111110000101 => 9223372036854775685
My incredibly hacked-together solution, tested only on your case:
public static long makeLong(String input) {
if(input.substring(0,1).equals("1")) {
return -1 * (Long.MAX_VALUE - Long.parseLong(input.substring(1), 2) + 1);
} else {
return Long.parseLong(input, 2);
}
}
Basically, if the first bit is a one, the number is negative, so we parse the rest of the number as a positive, then do some two's complement magic by subtracting that result from Long.MAX_VALUE
and adding one, then forcing the negative back onto the number returned. Otherwise, the normal conversion applies.
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