添加具有不同大小的二进制数组 [英] Adding binary arrays with different size
问题描述
我用数字及其每行的位长制成二进制数组,如果295289042101659每行6位,数字大小为49位,那么在数组中,它将是6位X 9行,通过代码并修改为6位长度零填充线:
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
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
如果我得到一些大小为3的402(0b110010010)数组,那么如何通过上下坐标或在点(3,6)的上下坐标将其添加到点(2,2)处上,从右到左的坐标? 它应该看起来像是:
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
00 11 11
001 1 01
000 1 01
010110
011101
011110
010110
011011
000001
001111
001101
000101
010110
011101
011110
010110
011011
我这样做是这样的:
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?
推荐答案
由于您提到了numpy标签,因此可以使用它来具有高性能和可读代码:
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)
对于:
[[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]]
这篇关于添加具有不同大小的二进制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!