bit representation in python

Viewed 373

Hi I have a question about the bit representation in python

when I use bit operation 1<<31, then we can see the bits are

1000 0000 0000 0000 0000 0000 0000 0000

python will print this value as 2147483648

but when I give a variable value like a = -2**31

the bits are also

1000 0000 0000 0000 0000 0000 0000 0000

but python will print -2147483648

so if the bits are the same , how python decide to use 2147483648 or -2147483648 ?

2 Answers

The representation isn't really the same. You can use int.to_bytes to check it:

(1 << 31).to_bytes(32, 'big', signed=True)

b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00'

(-2 ** 31).to_bytes(32, 'big', signed=True)

b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x80\x00\x00\x00'

Also, be careful about the - operator, which have the lower priority here:

-2 ** 31 == -(2 ** 31)

In python integers do not have a limited precision. Which means among other things, that the numbers are not stored in twos compliment binary. The sign is NOT stored in the bit representation of the number.

So all of -2**31, 2**31 and 1<<31 will have the same bit representation for the number. The sign part of the -2**31 is not part of the bitwise representation of the number. The sign is separate.

You can see this if you try this:

>>> bin(5)
'0b101'
>>> bin(-5)
'-0b101'
Related