Extract LSB bit from a Byte in python

2019-07-18 15:55发布

I have a byte in varibale '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...

2条回答
Evening l夕情丶
2楼-- · 2019-07-18 16:17

Right shift by the number n and take the last bit by and 1

num >> n &1
查看更多
祖国的老花朵
3楼-- · 2019-07-18 16:31

Is your "byte" an int? If so, just take bitwise AND (&) with 1 (or, if you want to be more explicit, the binary literal 0b1) to get the least significant bit.

>>> x = 14
>>> x & 1
0
>>> x = 15
>>> x & 1
1

Is your "byte" a bytes object? If so, just index into it and take bitwise AND.

>>> y = bytes([14, 15])
>>> y[0] & 1
0
>>> y[1] & 1
1
查看更多
登录 后发表回答