Basicly I just need to know the position of the highest 1 bit inside of an int or unsigned int. Like:
00001111=4;
00011111=5;
11111111=8;
Because I am sure that any number I will get will have consecutive 1 bits. 0...0000011...1 There will be no ..00010011... or something. So method can find the highest 1 or just count 1s. No matter.
This is the best I managed to do:
Uint32 number;
int shift=16; int segment=8;
while (segment)
{
if (number>>shift!=0) shift+=segment;
else shift-=segment;
segment>>1; // /2
}
you can try something like
Yes, the fastest way is lookup table.
(1)
you could count how many times you would have to bitshift your unsigned int until it was zero?
see What are bitwise shift (bit-shift) operators and how do they work?
or
(2)
example
number: 0111
bitshift one to the right: 0011, use bitwise x-or with original number 0111 ^ 0011 = 0100
in cpp:
Others have given a variety of answers, but it's probably worth mentioning that there is an entire book full of these kinds of things — Hacker's Delight by Henry S. Warren Jr., ISBN 978-0-201-91465-8, which also has a web page.
It's also worth highlighting the fact that some microprocessors have special support for some of these kinds of things. Lasse Reinhold's answer, above, makes use of that fact, but doesn't call the reader's attention to it. Generally speaking, except for very simple cases (like bit rotate instructions), compilers can't optimise “bit twiddling” algorithms to a single machine instruction, so if you know you’re on a machine that has e.g. a bit-scan-forward or population count instruction or similar, and you're in a position to use it (via either compiler intrinsics or
asm
statements), you might want to do so.Finally, since the question started by saying that the number was known to be of the form 0...000111...1, I'll add another option, based on computing (in parallel) the sums of the groups of bits:
Below code might help to count consecutive 1 bits.
Copy/paste of my function for it: