3

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 ?

1
  • How do you "see" the bits? Commented Jul 13, 2020 at 4:44

2 Answers 2

2

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'
Sign up to request clarification or add additional context in comments.

Comments

2

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)

2 Comments

This is misleading. The effect you are showing is a result of the to_bytes() call which changes the number from its normal internal python format. They are not stored as two compliment, so the positive and negative really do have the same bit patterns, because the sign is not saved as part of the bitwise representation of the number.
This is a python specific thing, you would be correct in most other languages like C or Java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.