Negative numbers in signed binary = bizarro world.
def toBinary(num, length=8):
'''Convert a decimal number to a signed binary number of given length.'''
capacity = 2 ** length
assert type(num) == int and -capacity / 2 <= num < capacity / 2
bits = ['0'] * length
n = (capacity + num) % capacity
i = length - 1
while i >= 0 and n > 0:
bits[i] = str(n % 2)
n //= 2
i -= 1
return ''.join(bits)
for i in range(-8, 8):
print('{0:2}: {1:4}'.format(i, toBinary(i)))
-8: 11111000
-7: 11111001
-6: 11111010
-5: 11111011
-4: 11111100
-3: 11111101
-2: 11111110
-1: 11111111
0: 00000000
1: 00000001
2: 00000010
3: 00000011
4: 00000100
5: 00000101
6: 00000110
7: 00000111