7

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...

LuxuryMode
  • 33,401
  • 34
  • 117
  • 188
3lokh
  • 891
  • 4
  • 17
  • 39

3 Answers3

20

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
senshin
  • 10,022
  • 7
  • 46
  • 59
  • @Nikhil When you read a file in binary mode (`rb`), you get a `bytes` object from `file.read()`. To find the least significant bit, take bitwise AND with `0b1`. Note that you will need to figure out which parts of the file are header and which parts are actual image data. It may help to use a library like PIL. – senshin Jan 24 '14 at 20:23
7

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".

fr_andres
  • 5,927
  • 2
  • 31
  • 44
-2

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

num >> n &1
ASHISH R
  • 4,043
  • 1
  • 20
  • 16