What is the fastest way to read the Left-Most bit from unsigned int ?
Leftmost set bit can be easily found by simply right shifting the given number “N” till that number is > 0. Alongside, we increment the position variable to find the position of the leftmost set bit.
The most significant bit (MSB) is the bit in a multiple-bit binary number with the largest value. This is usually the bit farthest to the left, or the bit transmitted first in a sequence. For example, in the binary number 1000, the MSB is 1, and in the binary number 0111, the MSB is 0.
In a binary number, the bit furthest to the left is called the most significant bit (msb) and the bit furthest to the right is called the least significant bit (lsb). The MSB gives the sign of the number (sign bit) , 0 for positive and 1 for negative. The remaining bits hold the magnitude of the number.
It's helper to compute the 2-based logarithm of integer number, i.e. it return the index of highest set bit in the number (or -1 for 0). I.e. for 1 it will return 0, for 16 it will return 4, for 1024 it will return 10, etc.
i >> (sizeof(unsigned int) * CHAR_BIT - 1)
The sizeof
, multiplication, and subtraction will be computed at compile-time by any reasonable compiler, so this should become a single right-shift instruction, which is about as fast as you will get.
Might be faster than shifting at run-time, if AND is faster than shifting:
i & (1 << (sizeof(unsigned int) * CHAR_BIT - 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