Ad

Adding Binary Arrays With Different Size

- 1 answer

I made binary arrays from number and its bit length per line, if 295289042101659 with 6 bits per line, number sizes 49 bit so in array, it would be 6 bits X 9 line, through the code and modified to 6-length zero filled lines:

def listify(a, bit = 5):
    res = []
    while a:
        a, b = divmod(a,2**bit)
        res.append(b)
    return res[::-1]

000001
000011
001001
000001
010110
011101
011110
010110
011011

Since it is binary array, I used binary addition code without carrying:

def binaryadd(one, other):
    if one & other:
        return False
    return one | other

If I get some array of 402(0b110010010) with size 3, then how could I add into the array at point(2,2) by up-to-down coordinate, or (3,6) from down-to-up, right-to-left coordinate? It should be seemed as:

000001
001111
001101
000101
010110
011101
011110
010110
011011

I've done it like this:

def array_add(one,another, point = (0,0)):
    a = [a*2**point[0] for a in another[:]]
    a+=[0]*point[1]
    a = [0]*(len(one)-len(a))+a
    res = [binaryadd(a,b) for a, b in  zip(one[::-1],a[::-1])][::-1]
    if not all(res):
        return False
    return res

Is the best way to do it, is to apply binary addition to every values of list, by modifying one list?

Or am I misunderstanding the basics of array?

Ad

Answer

Since you mention the numpy tag, you can use it to have high performance and readable code :

import numpy as np

def int_to_array(n,width):
    v=np.zeros(64,np.uint8)
    i,u,total=0,n,0
    while(u):
      if i%width == 0 : total += width  
      u,v[i],i = u//2,u%2,i+1
    return v[:total][::-1].reshape(-1,width)  

def add(a,b,point=(0,0)):
    sx,sy = point
    ex = sx+b.shape[0]
    ey = sy+b.shape[1]
    a[sx:ex,sy:ey] |= b

a=int_to_array(295289042101659,6)
b=int_to_array(402,3)
print(a)
print(b)
add(a,b,(2,2))   
print(a)

For :

[[0 0 0 0 0 1]
 [0 0 0 0 1 1]
 [0 0 1 0 0 1]
 [0 0 0 0 0 1]
 [0 1 0 1 1 0]
 [0 1 1 1 0 1]
 [0 1 1 1 1 0]
 [0 1 0 1 1 0]
 [0 1 1 0 1 1]]

[[1 1 0]
 [0 1 0]
 [0 1 0]]

[[0 0 0 0 0 1]
 [0 0 0 0 1 1]
 [0 0 1 1 0 1]
 [0 0 0 1 0 1]
 [0 1 0 1 1 0]
 [0 1 1 1 0 1]
 [0 1 1 1 1 0]
 [0 1 0 1 1 0]
 [0 1 1 0 1 1]]
Ad
source: stackoverflow.com
Ad