-
Notifications
You must be signed in to change notification settings - Fork 62
Open
Description
This code does not work properly when x contains most significant bit set to 1, e.g. 0xFFFFFFFF.
Maybe this solution might avoid this problem:
- Main idea is to shift right and add
0x1to set bit - Save if
(x == 0)to return 0 in this case:unsigned add_bit = (x == 0); - After setting all right bits to 1, shift right:
x >>= 1; - Add bit:
return (x + add_bit);
So the code will look like this:
int leftmost_one(unsigned x)
{
unsigned add_bit = (x != 0);
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
x >>= 1;
return (x + add_bit); // Add 1 if x != 0, 0 otherwise
}
Thanks!
Metadata
Metadata
Assignees
Labels
No labels