الخميس، 26 ديسمبر 2013

clarification needed on Java's 32-bit integer representation system?

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 11111111and 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

View the original article here

ليست هناك تعليقات:

إرسال تعليق