0

I am trying to covert and array filed with decimals from 0 to 63 , x=[0 1 2 ... 63] into an array with the equal binaries, but I get the following error: "invalid literal for int() with base 10: '0b0'". My code is the following (in Python) :

g=np.arange(0,64,1)
for x in range(0,64,1):
    g[x]=bin(g[x])

I am new to python, so if anyone can find my mistake (logic or syntax) I would appreciate any help. extra: Is there any way to make the binaries 6 bits that get put in the array?

2 Answers2

0

You will have to store them as strings representing binary numbers.

>>> x=0x1011   # hex
>>> x
4113           #just another number under the hood
>>> x=0b1011
>>> x
11
>>> x=str(0b1011)
>>> x
'11'
>>> x=str(bin(11))
>>> x
'0b1011'
>>>

bin_list = []
for each in range(64):
    bin_rep = str(bin(each))
    bin_rep = bin_rep[:2] + bin_rep[2:].zfill(6)
    bin_list.append(bin_rep)

print(bin_list)

Not as concise as another comment but possibly more easy to follow for someone new to Python... Hope this helps!

srattigan
  • 665
  • 5
  • 17
0

Using Python 3: Initialize the g array first, then append it in the loop.

g = '{0:06b}'.format(0)

for x in range(1,64,1):
    g=np.append(g,'{0:06b}'.format(x))

print(g)

extra: Python is very well documented

hth

mr_orange
  • 121
  • 1
  • 5