I am reviewing the bit offset in java but it seems very curious to me that bit 32 gives me a negative. I assume that it is due to the INT(32bits) data type and that it has a limit of bytes, but it would help me a lot if someone clarified it for me. .
For example:
here it moved 30 times, that is, it stayed in bit 31
System.out.println(0B1 << 30);// es 1073741824 en base 10
here I scroll 31 times I stay in bit 32
System.out.println(0B1 << 31);// es -2147483648 en base 10
here it moved 32 times, it stayed in bit 33, that is, it went to byte 5
System.out.println(0B1 << 32);// es 1 en base 10
Actually the last bit does not represent the sign, it is an error to make that approach. If it were that way, then the
1
decimal value, using 4 bits to simplify instead of 32, would render0001b
and the-1
would render1001b
, and it doesn't. The value1001b
represents the-7
decimal value.What happens is that in 2's complement negative values are represented by taking the positive value, negating all bits, and then adding
1
. For example:The value
3
, expressed in 4-bit, binary, is0011b
. To represent the value-3
, all the bits are inverted, leaving then1100b
and then adding1b
, giving the final result that is1101b
.As a side effect, all negative numbers have their most significant bit in value
1
, and the most significant bit of your 32-bit integer in Java is bit 31.The largest negative number that can be represented in 2's complement is the one with its most significant bit in
1
and the remainder in0
.The formal representation for the negative number of a 2's complement value
N
is ( 2 ^n)-N , where n is the number of bits and N is the value to represent.