Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return index of least significant bit in Python

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.

like image 787
brannerchinese Avatar asked Apr 02 '11 02:04

brannerchinese


People also ask

How do you find the least significant bit 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.

How do you extract the least significant bit?

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)

How do I find MSB and LSB?

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.

How do I find MSB?

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.


1 Answers

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
like image 86
David Jones Avatar answered Oct 25 '22 03:10

David Jones