C++ has a set of functions, ffs(), ffsl(), and ffsll(), that return the least significant bit that is set in a given binary integer.
I'm wondering if there is an equivalent function already available in Python. I don't see one described for bitarray, but perhaps there's another. I am hoping to avoid calculating the answer by looping through all possible bit masks, though of course that's an option of last resort; ffs() simply returns a single integer and I'd like to know of something comparable in Python.
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.
A simple solution is to one by one divide n by 2 until it becomes 0 and increment a count while doing this. This count actually represents the position of MSB.
Only in Pythons 2.7 and 3.1 and up:
def ffs(x):
"""Returns the index, counting from 0, of the
least significant set bit in `x`.
"""
return (x&-x).bit_length()-1
Example:
>>> ffs(136)
3
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