Search code examples
pythonnumpybitwise-and

extract channels from bit wise encoded array


I got an array with bitwise encoded 3 channels. like this:

1 for channel 1
2 for channel 2
3 for channel 1 and 2
4 for channel 3
5 for channel 1 and 3
6 for channel 3 and 2

I know how to do it in Matlab bitand(digital_word, 2^1) with bitwise and, but if I try to do the same for python with eg. for channel 1 np.bitwise_and(digital_word, 2^1) I get gibberish out

I want to get out a one for a given channel if the channel is encoded by the bit.

Some examples:
input:

 array([0,0,1,0,1,0,3,4,5,6])

output:

channel 1: [0,0,1,0,1,0,1,0,1,0]
channel 2: [0,0,0,0,0,0,1,0,0,1]
channel 3: [0,0,0,0,0,0,0,1,1,1]

Solution

  • I'm not sure what you meant to achieve by using 2^1, but using np.bitwise_and was the correct approach.

    For example, you get the result for channel 1 with np.bitwise_and(digital_word, 1):

    >>> digital_word = np.array([0,0,1,0,1,0,3,4,5,6])
    >>> np.bitwise_and(digital_word, 1)
    array([0, 0, 1, 0, 1, 0, 1, 0, 1, 0])
    

    For the higher-valued bits the result is almost what you want, but you need to right-shift it to get 1 instead of 2n.

    >>> np.bitwise_and(digital_word, 2)
    array([0, 0, 0, 0, 0, 0, 2, 0, 0, 2])
    >>> np.bitwise_and(digital_word, 2) >> 1
    array([0, 0, 0, 0, 0, 0, 1, 0, 0, 1])
    

    Note that to get the third bit, you need to bitwise-and with 4 (= 23–1), not 3:

    >>> np.bitwise_and(digital_word, 4)
    array([0, 0, 0, 0, 0, 0, 0, 4, 4, 4])
    >>> np.bitwise_and(digital_word, 4) >> 2
    array([0, 0, 0, 0, 0, 0, 0, 1, 1, 1])
    

    In general, to get the nth bit:

    np.bitwise_and(digital_word, (1 << n)) >> n
    

    NumPy arrays also support the & bitwise operator, so this is equivalent:

    (digital_word & (1 << n)) >> n