I am trying to convert an array with integers to binary, using python 2.7.
A simplified version of my code is the following:
#!/usr/bin/python
import numpy as np
a=np.array([6,1,5,0,2])
b=np.array(np.zeros((5)))
for i in range(10):
b[i]=bin(int(a[i])).zfill(8)
The code gives me the error message:
b[i]=bin(int(a[i])).zfill(8)
ValueError: invalid literal for float(): 0000b110
What is wrong with my code?
Is there another way to do this?
The original code is part of a much greater project with 2 dimensional arrays.
p.s I'm a relative novice to Python
解决方案
Numpy attempts to convert your binary number to a float, except that your number contains a b which can't be interpreted; this character was added by the bin function, eg. bin(2) is 0b10. You should remove this b character before your zfill like this by using a "slice" to remove the first 2 characters:
b[i]=bin(int(a[i]))[2:].zfill(8)