Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to read Left-Most bit from unsigned int (C++)?

What is the fastest way to read the Left-Most bit from unsigned int ?

like image 502
Shachar Weis Avatar asked Jul 27 '10 14:07

Shachar Weis


People also ask

How do I get my left bit the most set?

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.

How do I find MSB?

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.

What is left most bit?

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.

What is __ LG in C++?

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.


2 Answers

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.

like image 164
Tyler McHenry Avatar answered Oct 18 '22 03:10

Tyler McHenry


Might be faster than shifting at run-time, if AND is faster than shifting:

i & (1 << (sizeof(unsigned int) * CHAR_BIT - 1))
like image 33
Douglas Leeder Avatar answered Oct 18 '22 05:10

Douglas Leeder