I have a byte in variable 'DATA'. I want to extract the LSB bit out of it and print it. I'm very new to python, I found many articles with complex bitwise addition logic and all which was very tough to understand. I'm looking for a simple logic like we do with the strings eg DATA[7:1] Please help me out...
Extract LSB bit from a Byte in python
36.6k Views Asked by nkg At
3
There are 3 best solutions below
0

Simplest and probably fastest:
least_significant_bit_of_x = x & -x
You can find more tricks here: https://www.informit.com/articles/article.aspx?p=1959565
Although the go-to reference for bitwise "black magic" is Knuth's "The Art of Computer Programming, vol. 1".
Is your "byte" an
int
? If so, just take bitwise AND (&
) with1
(or, if you want to be more explicit, the binary literal0b1
) to get the least significant bit.Is your "byte" a
bytes
object? If so, just index into it and take bitwise AND.