Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python binary arithmetic

I've been doing binary arithmetic in Python. It seems clumsy to me probably because there is a better way. The sample code provided creates a binary digit list, creates the reverse list and create the absolute difference. any suggestions for better technique will be appreciated.

 for (i, j, k, n, m) in [(i, j, k, n, m)for i in range(2) for j in range(2) \
                for k in range(2)for n in range(2) for m in range(2)]:

s = [i, j, k, n, m]  # binary sequence
r = s[::-1]      # reversed sequence

sbin = '0b'      # create binary number as string
rbin = '0b'
for a in range(5):
    sbin += str(s[a])
    rbin += str(r[a])

sbb = int(sbin,2)  # create binary number
rbb = int(rbin,2)
v = abs(sbb - rbb)  # take absolute difference as integers

dif = bin(v)            # convert back to binary
print(sbin, rbin, dif, v)
like image 649
Graybits Avatar asked Dec 31 '25 06:12

Graybits


1 Answers

this is an option:

BITSIZE = 5

for i in range(1<<BITSIZE):
    a = i
    b = 0
    for k in range(BITSIZE):  # b = reversed_bits(a)
        b <<= 1
        b ^= i&1
        i >>= 1
    print('   {:05b} {:05b}'.format(a, b))
    print(a, b, abs(a-b))

instead of enumerating the individual bits, the first loop counts from 0 to 2^5-1 (1<<5 shifts a bit up 5 places which equals to 2^5). the rest is just a matter of reversing the bits (the loop over k).

this outputs:

   00000 00000
0 0 0
   00001 10000
1 16 15
   00010 01000
2 8 6
   00011 11000
3 24 21
   00100 00100
4 4 0
   00101 10100
5 20 15
...
   11110 01111
30 15 15
   11111 11111
31 31 0

the binary operations of python can be seen here: https://wiki.python.org/moin/BitwiseOperators


as pointed out by Reti43 this could be written a little more compact:

BITSIZE = 5
for a in range(1<<BITSIZE):
    b = 0
    for k in range(BITSIZE):  # b = reversed_bits(a)
        b = (b << 1) | ((a >> k) & 1)
    print(a, b, abs(a-b))
like image 129
hiro protagonist Avatar answered Jan 01 '26 20:01

hiro protagonist