Reputation: 23
I'm having trouble finding a way to convert from a 32-bit two's complement binary number to a decimal in java. I either get an overflow error or the number comes out nonnegative when it should be negative.
String bin = "11111111111111111111111111111110";
long foo = Long.parseLong(bin);
System.out.println(foo);
This is one of the things I tried and I was thinking I needed to use long because it can hold up to 64-bits. Any help would be great. Thanks
Upvotes: 1
Views: 3844
Reputation: 881293
You need to provide the base, or radix, of two if you want to parse a binary value.
long foo = Long.parseLong(bin, 2);
You can see an example on the Java doc page:
parseLong("1100110", 2)
returns102L
.
Without the radix, it uses base-10, and 1032
won't fit into a long
.
Keep in mind that, for a 32-character bit string, this will give you the unsigned variant. If you want the signed variant in a long
, you can use:
if (foo > 0x7fffffffL) foo = -(0x100000000L - foo);
afterwards to adjust it
Or you can forcefully cast it to an integer if that's suitable:
int foo = (int)Long.parseLong(bin,2);
The requirement that Integer.parseInt()
be given a signed number means that it's unsuitable as-is for 32-character binary strings with a leftmost 1-bit.
Upvotes: 3
Reputation: 121639
You're correct - you need to use "Long" in this case.
Since you're doing twos complement (not ones complement), you can use "parseLong()" with a radix of "2":
public class X {
public static void main (String[] args) {
String bin = "11111111111111111111111111111110";
int i = (int)Long.parseLong(bin, 2);
System.out.println("parseInt(" + bin + ", 2)=" + i);
}
}
// Output:
parseInt(11111111111111111111111111111110, 2)=-2
Upvotes: 0
Reputation: 26067
radix
is the base of the used numbering system.
public static void main(String[] args) {
int bits = (int) Long.parseLong("11111111111111111111111111111110", 2);
System.out.println(bits);
}
output
-2
Upvotes: 0