Least Significant 1 Bit

| No Comments

This can be useful for extracting the lowest numbered element of a bit set. Given a 2's complement binary integer value x, (x&-x) is the least significant 1 bit. The reason this works is that it is equivalent to (x & ((~x) + 1)); any trailing zero bits in x become ones in ~x, adding 1 to that carries into the following bit, and AND with x yields only the flipped bit... the original position of the least significant 1 bit.

Alternatively, since (x&(x-1)) is actually x stripped of its least significant 1 bit, the least significant 1 bit is also (x^(x&(x-1))).

Leave a comment

About this Entry

This page contains a single entry by Pete Shanahan published on November 30, 2005 1:29 PM.

Integer Selection was the previous entry in this blog.

Did you get your 360 today? is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.