Maddel - 1 year ago 166
Python Question

# Convert a byte array to single bits in a array [Python 3.5]

I am looking for a operation witch converts my byte array:

``````mem = b'\x01\x02\xff'
``````

in something like this:

``````[ [0 0 0 0 0 0 0 1]
[0 0 0 0 0 0 1 0]
[1 1 1 1 1 1 1 1] ]
``````

These are operations that I tried:

``````import numpy as np

mem = b'\x01\x02\xff' #define my input
mem = np.fromstring(mem, dtype=np.uint8) #first convert to int

#print(mem) give me "[  1   2 255]" at this piont

mem = np.array(['{0:08b}'.format(mem[b]) for b in mem]) #now convert to bin
data= np.array([list(mem[b]) for b in mem]) #finally convert to single bits

print(data)
``````

This code will crash at line 4..
`IndexError: index 255 is out of bounds for axis 0 with size 9`

Otherwise, it crash at line 5..
`IndexError: too many indices for array`

These are my Questions:

Why are the number of spaces different after the conversion from hex to int?

Is that the reason that my next conversion from int to bin failed?

Finally, what is wrong with my
`list`
operation?

Thank you for your help! :)

Using unpackbits:

``````>>> import numpy as np
>>> mem = b'\x01\x02\xff'
>>> x = np.fromstring(mem, dtype=np.uint8)
>>> np.unpackbits(x).reshape(3,8)
array([[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1]], dtype=uint8)
``````

### Documentation

From `help(np.unpackbits)`:

unpackbits(...)
unpackbits(myarray, axis=None)

Unpacks elements of a uint8 array into a binary-valued output array.

Each element of `myarray` represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if `axis` is None) or the same shape as the input array with unpacking done along the axis specified.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download