This could be a very basic question. but I want to understand basic concepts clearly first. The question is about the bit representation of integers in java.

In Java integers are represented in 32-bits. int y = 3; is represented as 00000000 00000000 00000000 00000011

The 32nd bit is the signed bit, which is used to indicate the sign (0 if + and 1 if -ve) what I don't understand is how and why the integers are wrapped when signed: example:

y —->00000000 00000000 00000000 00000011 //3
x — > 11111111 11111111 11111111 11111101  // -3

while it should be: 10000000 00000000 00000000 00000011 // -3

when it is 3://00000000 00000000 00000000 00000011,

I could get the decimal value by 1^0 + 2 ^1, by looking at the turned on bits

when it is -3://11111111 11111111 11111111 11111101 I see it is not easy to calculate the the decimal value. if -3 is represented as 10000000 00000000 00000000 00000011: using the first bit, I get -ve, and the usual decimal calculation can be done to get 3

similarly for the integer max with -ve sign only the 1st and 32nd bit are turned on:

-2147483647  —> 10000000 00000000 00000000 00000001
-2 —>           11111111 11111111 11111111 11111110
-1 —>           11111111 11111111 11111111 11111111 

I dont understand how to read these bits to get the decimal value or how exactly is -1 represented by turning on all the bits.

Thanks for lending help.

有帮助吗?

解决方案

As suggested by @clcto in comments, check out the 2s complement representation.

https://en.wikipedia.org/wiki/Two%27s_complement

其他提示

Let's talk about 8 bits for simplicity. In unsigned arithmetic, this would just be

00000011 = 0 * 2^7 + 0 * 2^6 + 0 * 2^5 + 0 * 2^4 + 0 * 2^3 + 0 * 2^2 + 1 * 2^1 + 1 * 2^0

In the twos complement representation, -1 is represented as

11111111 = 1 * -(2^7) + 1 * 2^6 + 1 * 2^5 + 1 * 2^4 + 1 * 2^3 + 1 * 2^2 + 1 * 2^1 + 1 * 2^0

The only difference in twos complement notation is that the top bit represents the negation of the number it would normally represent.

This representation turns out to be much more convenient.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top