As a rule, the least significant bit is index bit 0, and the most significant bit is index bit 7. Using this terminology, we can determine if bit index k is set, bitwise and with 1 shifted to the left by k. If bitwise and non-zero, then this means that the index k has 1; otherwise, the index k has a value of 0. So:
def get_bit (byteval, idx):
return ((byteval & (1 << idx))! = 0);
This will correctly determine the value of the bits from the 0 ... 7 byte indices going from right to left (i.e., the least significant bit to the most significant bit or equivalently from 1st place to 2 7 = 128th place).
Why does it work
I decided that I should add an explanation of why it works ...
1 <0 - 1 = 0000 0001
1 <1 is 2 = 0000 0010
1 <2 is 4 = 0000 0100
As you can see, 1 <k is equivalent to 2 k and contains 1 in the index that interests us exactly and in no other place. Therefore, bitwise and with 1 <k will either return 0 or 1 <k; it will be 0 if the bit in the index of interest to us is 0 (because 1 and 0 are 0, and all other bits in 1 <k are equal to zero). If the bit that we are interested in is 1, then we get 1 and 1 at that position, and 0 and something else, everywhere.
source share