0

I have a large array of integers. I want to convert it to an array of their binary representations in an efficient way.

Here's an example with a small array of what I'm looking for,

    array = np.array([1,4,1111],dtype=np.uint16)

    want = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
                     [0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0],
                     [0,0,0,0,0,1,0,0,0,1,0,1,0,1,1,1]
                    ]
                    ,dtype=np.uint8)

There are various ways how this can be done iteratively, with the help of e.g. '{:016b}'.format(integer) but I need an efficient way of doing it, since my array of integers contains hundreds of thousands of integers, and this operation is used repeatedly in my code.

In other words, what I'm looking for is the function np.unpackbits, except I need the dtype of the output array of bits to be larger than np.uint8 [e.g. np.uint64].

A suggested solution:

    array = np.array([[1],[4],[1111]],dtype=np.uint16)
    np.unpackbits(array.view(np.uint8),axis=1)

doesn't give correct results compared to '{:016b}'.format(integer).

Any ideas are much appreciated!

python_freak
  • 259
  • 3
  • 12

0 Answers0