I need some clarifications regarding the binary representation of decimal in Java (or any other language for that matter).
pardon, if this is too basic, but I need to understand it thoroughly.
x = 31 is represented in Java 32 bit as:
x — > 00000000 00000000 00000000 00011111 //
the binary to decimal conversion is achieved by:
2^4+2^3+2^2+2^1+2^0=31
Now, if you consider all the bits turned on, except the signed bit (most significant bit)
, we get
y -> 01111111 11111111 11111111 11111111
and binary to decimal conversion by summing powers of 2 will be:
2^31+2^30………+2^3+2^2+2^1+2^0=4294967295.
however, if you do:
System.out.println(Integer.parseInt("1111111111111111111111111111111",2));
you get: 2147483647 which is 2^31-1
so it means, the when 31 bits
are turned on, I do not get the additive sum of the powers of 2.
why is this?
may be I did not understand something, if some one could clarify that will be very helpful.
In case this helps: All the two raise powers till 31 are in this list:
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648]
EDIT: I corrected the y
-representation, now it has 32 bits, but if you calculate the 31 bits that are turned on with summing the powers, you would get 4294967295. I have one liner in python here
>>> reduce(lambda x,y: x+y, [pow(2,i) for i in range(32)])
4294967295
so it means, the when 31 bits are turned on, I do not get the additive sum of the powers of 2.
Yes you do - you get 20 + 21 + 22 + 23 + ... + 230... which is 231 - 1, exactly as you're seeing.
You're not adding 231 because that would be represented by a 32nd 1
, at which point you'd be beyond the limit of what an int
can represent in Java.
It's probably easier to consider smaller numbers. Suppose you have 5 bits - your example earlier on:
Integer.parseInt("11111")
That would print out 31, exactly as you said before... because 31 is 25 - 1.
So for n
bits all set to 1, you get 2n - 1... which is correct for your example with 31 bits. There's nothing inconsistent here.
See more on this question at Stackoverflow