Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit representation in python

Tags:

python-3.x

bit

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 ?

like image 342
Aaron Wei Avatar asked Apr 09 '26 20:04

Aaron Wei


1 Answers

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'
like image 139
Glenn Mackintosh Avatar answered Apr 12 '26 14:04

Glenn Mackintosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!