3

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

tdelaney
  • 73,364
  • 6
  • 83
  • 116
Marios K.
  • 51
  • 1
  • 1
  • 8
  • Possible duplicate of [Converting integer to binary in python](http://stackoverflow.com/questions/10411085/converting-integer-to-binary-in-python) – Reti43 Mar 21 '16 at 18:22
  • The ValueError comes from the fact that you created an accidental monstrosity. bin(6) is `'0b110'` and you needed to get rid of the `0b` part before padding with 0s. The error message literally points out that there is something wrong with `0000b110`. Also, why are your array of size 5 but you do `for i in range(10):`? – Reti43 Mar 21 '16 at 18:25
  • Thank you all for your quick response! – Marios K. Mar 22 '16 at 17:25
  • The size of the array (10) was set accidentally. In the original code it is correct. – Marios K. Mar 22 '16 at 17:28

2 Answers2

4

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)
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
1

bin will create a string that starts with 0b indicating that it is a binary representation. If you only want the binary representation you have to slice the first two characters before you call zfill.

Instead of doing this, you could use format like so

b[i] = '{:08b}'.format(a[i])

Basically, this will print the binary representation of a[i] padded with 0 until it has length 8.

See the Format Specification Mini-Language for further details.

kmario23
  • 57,311
  • 13
  • 161
  • 150
AlexV
  • 578
  • 8
  • 19