Python `bin` negative integers

I tried repeating the Pycon2010 Brandon Rhodes' Powerful Dictionary conversation , and noticing that I could not use the built-in binpython to compute the least significant bits of the hash:

>>> bin(hash("ftp"))[-3:]
'111'

What a conversation should be 001.

After a little digging, I found that I had to use this regular function bitslike Brandon:

>>> def bits(integer):
       return "".join(str(x) for x in [1&(integer>>i) for i in range(32)[::-1]])

>>> bits(hash("ftp"))[-3:]
'001'

Apparently, since the builtin binreturns bits as signed binary strings:

>>> bits(-100)
'11111111111111111111111110011100'  # two-complement representation preceded by 1s
>>> bin(-100)
'-0b1100100'  # signed magnitude representation

Why is this so? Is there any special reason not to return a two component representation of a negative integer in python?

+4
1

Python : -1 1 s.

+2

Source: https://habr.com/ru/post/1616527/


All Articles