Reputation:
I want to generate all binary numbers within a specific range, the code I have so far is:
int2binary = {}
largest_number = pow(2,16)
binary = np.unpackbits(np.array([range(largest_number)],dtype=np.uint16).T,axis=1)
As the numbers generated will be higher than an 8-bit binary number can show, I have changed the dtype from np.uint8
(which works) to np.uint16
which then returns the error:
binary = np.unpackbits(np.array([range(largest_number)],dtype=np.uint16).T,axis=1)
TypeError: Expected an input array of unsigned byte data type
How am I able to fix this error? I have looked on the NumpPy
website for their datatypes and uint16
is on there so I am not sure why this isn't working.
Update
Using Abhisek Roy's answer, the error is no longer there. However I forgot to add an import part of the code which is giving a new error:
int2binary[i] = b[i]
IndexError: index 1 is out of bounds for axis 0 with size 1
For the loop:
for i in range(largest_number):
int2binary[i] = b[i]
Upvotes: 4
Views: 3172
Reputation: 1
largest_number = pow(2,binary_dim)
midbinary = []
binary =[]
for i in range(largest_number):
midbinary.append(format(i, '08b').zfill(16))
for j in range(len(midbinary)):
b1=[]
for k in midbinary[j]:
b1.append(int(k))
binary.append(b1)
binary = np.array(binary)
for i in range(largest_number):
int2binary[i] = binary[i]
Upvotes: 0
Reputation: 2578
A view('uint8') of the uint16 array can do the trick:
#! /usr/bin/python3
import numpy as np
print(np.__version__)
int2binary = {}
largest_number = pow(2,16)
A = np.array(range(largest_number),dtype=np.uint16)
print(A)
print(A.ndim)
print(A.size)
print(A.flags)
print(A.itemsize)
print(A.nbytes)
B = A.view('uint8')
print(B)
print(B.ndim)
print(B.size)
print(B.flags)
print(B.itemsize)
print(B.nbytes)
binary = np.unpackbits(B)
print(binary)
print(binary.ndim)
print(binary.size)
print(binary.flags)
print(binary.itemsize)
print(binary.nbytes)
Upvotes: 0
Reputation: 584
I guess this is what you wanted. Ran this. It works. Check and tell.
import numpy as np
int2binary = {}
largest_number = pow(2,16)
a=(np.array([range(largest_number)],dtype=np.uint8))
b = np.unpackbits(a, axis=1)
for row in b:
x=row
for i in range(len(x)):
int2binary[(i)] = x[i]
print(int2binary)
Upvotes: 1