user288609 - 1 year ago 54

Python Question

I once read the following python function,

`def f1(i, num_digits):`

return np.array([i >> d & 1 for d in range(num_digits)])

I am not very clear on how does the part of

`i >> d & 1`

`f1(2,5)`

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

Answer Source

This function creates a list containing the last bit of `i`

after it got shifted `index`

times to the right.

Sounds cryptic? It is.

Here is what happens:

The list comprehension creates a list of size `num_digits-1`

, using the values of the range expression (which are 0 to `num_digits-1`

) to calculate the value of the item that is supposed to be at that index of the list. To calculate the value of the list item, the integer `i`

is taken and the bits of it are shifted to the right by `d`

places, where `d`

is the current value of the range we are iterating over to construct our list. The `>>`

(bitshift-right) operator has higher precedence than the `&`

operator, so this calculation is done first. The last step to calculating the list value is performing a logical `&`

of the bitshifted value and the value `1`

. This step requires some thinking, but what it does is it returns the last bit of our bitshifted value.

This is easier if you actually do the steps on a piece of paper. See, how the only time the last bit of our computation is 1 is if we shift the bit value of 2 to the right by one place (hence the list entry at index 1 is a 1 and the rest are 0's):

```
Index 0: 2 (dec) = 10 (bin) -> >> 0 -> 10 (bin) -> 10 & 01 = 00 (bin) = 0 (dec)
Index 1: 2 (dec) = 10 (bin) -> >> 1 -> 01 (bin) -> 01 & 01 = 01 (bin) = 1 (dec)
Index 2: 2 (dec) = 10 (bin) -> >> 2 -> 00 (bin) -> 00 & 01 = 00 (bin) = 0 (dec)
# From here on it will be the same as index 2, because we are only shifting 0's
```

I hope this helps you understanding what is going on.