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...
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.
To be sure you get the right bit/value: The value at the least significant bit position = x & 1. The value of the isolated least significant 1 = x & -x. The zero-based index of the isolated least significant 1 = log2(x & -x)
The 1 at the left side of the binary number is the MSB because it has a place value of 128, the highest value in the byte, and the 1 at the right side of the binary number is the LSB, which has a place value of 1, the lowest value in the byte.
Sometimes abbreviated as LSB, the least significant bit is the lowest bit in binary numbers. It is either the leftmost or rightmost bit in a binary number, depending on the computer's architecture.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With