Convert integer to binary array with suitable complement

I have integers in a range 0..2**m - 1, and I would like to convert them to numpy binary arrays of length m. For example, let's say m = 4. Now 15 = 1111in binary format, so there should be an output (1,1,1,1). 2 = 10in binary format, so there should be an output (0,0,1,0). If there mwere 3, then you 2should convert to (0,1,0).

I tried np.unpackbits(np.uint8(num)), but it does not give an array of the correct length. For example,

np.unpackbits(np.uint8(15))
Out[5]: array([0, 0, 0, 0, 1, 1, 1, 1], dtype=uint8)

I need a method that worked for anyone mthat I have in the code.

+4
source share
4 answers

, -

>>> d = np.array([1,2,3,4,5])
>>> m = 8
>>> (((d[:,None] & (1 << np.arange(m)))) > 0).astype(int)
array([[1, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 0, 0, 0, 0]])

, :

>>> (1 << np.arange(m))
array([  1,   2,   4,   8,  16,  32,  64, 128])
>>> d[:,None] & (1 << np.arange(m))
array([[1, 0, 0, 0, 0, 0, 0, 0],
       [0, 2, 0, 0, 0, 0, 0, 0],
       [1, 2, 0, 0, 0, 0, 0, 0],
       [0, 0, 4, 0, 0, 0, 0, 0],
       [1, 0, 4, 0, 0, 0, 0, 0]])

1 , (> 0)*1, .astype(bool).astype(int) .. .

+9

, numpy.binary_repr:

def bin_array(num, m):
    """Convert a positive integer num into an m-bit bit vector"""
    return np.array(list(np.binary_repr(num).zfill(m))).astype(np.int8)

:

In [1]: bin_array(15, 6)
Out[1]: array([0, 0, 1, 1, 1, 1], dtype=int8)

numpy :

def vec_bin_array(arr, m):
    """
    Arguments: 
    arr: Numpy array of positive integers
    m: Number of bits of each integer to retain

    Returns a copy of arr with every element replaced with a bit vector.
    Bits encoded as int8's.
    """
    to_str_func = np.vectorize(lambda x: np.binary_repr(x).zfill(m))
    strs = to_str_func(arr)
    ret = np.zeros(list(arr.shape) + [m], dtype=np.int8)
    for bit_ix in range(0, m):
        fetch_bit_func = np.vectorize(lambda x: x[bit_ix] == '1')
        ret[...,bit_ix] = fetch_bit_func(strs).astype("int8")

    return ret 

:

In [1]: vec_bin_array(np.array([[100, 42], [2, 5]]), 8)

Out[1]: array([[[0, 1, 1, 0, 0, 1, 0, 0],
                [0, 0, 1, 0, 1, 0, 1, 0]],

               [[0, 0, 0, 0, 0, 0, 1, 0],
                [0, 0, 0, 0, 0, 1, 0, 1]]], dtype=int8)
+2

"" .

def bin_array(num, m):
    """Returns an array representing the binary representation of num in m bits."""
    bytes = int(math.ceil(m / 8.0))
    num_arr = np.arange(num, num+1, dtype='>i%d' %(bytes))
    return np.unpackbits(num_arr.view(np.uint8))[-1*m:]     
0

, . , , np.unpackbits, . , python ints .

, m, "" . , ( 8) 1 . 0s preend 0s, :

m = 4
mval = np.unpackbits(np.uint8(15))

if len(mval) > m:
   mval = mval[m-len(mval):]
elif m > len(mval):
   # Create an extra array, and extend it
   mval = numpy.concatenate([numpy.array([0]*(m-len(mval)), dtype=uint8), mval])
0

Source: https://habr.com/ru/post/1530434/


All Articles