Two’s Complement Binary in Python?

It works best if you provide a mask. That way you specify how far to sign extend. >>> bin(-27 & 0b1111111111111111) ‘0b1111111111100101’ Or perhaps more generally: def bindigits(n, bits): s = bin(n & int(“1″*bits, 2))[2:] return (“{0:0>%s}” % (bits)).format(s) >>> print bindigits(-31337, 24) 111111111000010110010111 In basic theory, the actual width of the number is a … Read more