Python Question

Two Complement's Python (with as least bits as possible)

I am trying to output the binary representation of an negative number with the least bytes available each time.

Example:

-3 -> 101
-10 -> 10110

Answer

Here's a way to do this using the .bit_length method of Python 3 integers. It also uses the string .format method to do the integer to binary string conversion. This function returns a string starting with '0' for non-negative numbers so that they can be distinguished from negative numbers.

def twos_complement(n):
    m = n + 1 if n < 0 else n
    bitlen = 1 + m.bit_length()
    mask = (1 << bitlen) - 1
    return '{0:0{1}b}'.format(n & mask, bitlen)

for i in (-10, -3, 0, 3, 10):
    print('{:3}: {}'.format(i, twos_complement(i)))

print('- ' * 30)

for i in range(-15, 16):
    print(i, twos_complement(i))    

output

-10: 10110
 -3: 101
  0: 0
  3: 011
 10: 01010
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
-15 10001
-14 10010
-13 10011
-12 10100
-11 10101
-10 10110
-9 10111
-8 1000
-7 1001
-6 1010
-5 1011
-4 100
-3 101
-2 10
-1 1
0 0
1 01
2 010
3 011
4 0100
5 0101
6 0110
7 0111
8 01000
9 01001
10 01010
11 01011
12 01100
13 01101
14 01110
15 01111