Note that there are some explanatory texts on larger screens.

plurals
  1. POclarification needed on Java's 32-bit integer representation system?
    primarykey
    data
    text
    <p>I need some clarifications regarding the binary representation of decimal in Java (or any other language for that matter).</p> <p>pardon, if this is too basic, but I need to understand it thoroughly.</p> <pre><code>x = 31 is represented in Java 32 bit as: x — &gt; 00000000 00000000 00000000 00011111 // the binary to decimal conversion is achieved by: 2^4+2^3+2^2+2^1+2^0=31 </code></pre> <p>Now, if you consider all the bits turned on, except the <code>signed bit (most significant bit)</code>, we get</p> <pre><code>y -&gt; 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. </code></pre> <p>however, if you do:</p> <pre><code>System.out.println(Integer.parseInt("1111111111111111111111111111111",2)); you get: 2147483647 which is 2^31-1 </code></pre> <p>so it means, the when <code>31 bits</code> are turned on, I do not get the additive sum of the powers of 2. why is this?</p> <p>may be I did not understand something, if some one could clarify that will be very helpful.</p> <p>In case this helps: All the two raise powers till 31 are in this list:</p> <pre><code>[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] </code></pre> <p>EDIT: I corrected the <code>y</code>-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</p> <pre><code>&gt;&gt;&gt; reduce(lambda x,y: x+y, [pow(2,i) for i in range(32)]) 4294967295 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload