简体   繁体   中英

How to convert a numpy.array to binary?

I'm using the following function with Python2.7:

def array2int(pixels):
    out = 0
    for bit in pixels:
        out = (out << 1) | bit
    return out 

Which usually works, but if I pass

v=np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
array2int(v.astype(int))

it returns -262145 .

Unlike Python, numpy by default uses fixed size integers. Those can overflow:

1<<65
# 36893488147419103232 # correct
npone = np.ones([1], dtype=int)[0]
npone
# 1
type(npone)
# <class 'numpy.int64'>
npone<<65
# 2 # wrong

When adding or bitwise oring or whatever a python int and a numpy int, numpy typically wins and the result will be a numpy int:

out = 1
type(out)
# <class 'int'>
out = (out << 1) | npone
type(out)
# <class 'numpy.int64'>

To prevent that from happening in your function you can explicitly cast bit to a proper int :

        out = (out << 1) | int(bit)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM