If I have a binary number, say x = 00010000
, I can set all bits up to the highest and only set bit by doing y = x | (x - 1)
resulting in y = 00011111
.
How can I achieve the same result if multiple bits are set, e.g. x = 00010101
?
If I have a binary number, say x = 00010000
, I can set all bits up to the highest and only set bit by doing y = x | (x - 1)
resulting in y = 00011111
.
How can I achieve the same result if multiple bits are set, e.g. x = 00010101
?
This is a find first set problem
No possible solution with only bitwise operations. If you want to code it the usual way, think "binary search" for more efficient algorithms.
Here's something to get you started but I am sure there are more efficient algos out there
int findfirstset(unsigned int x) {
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return x - (x >> 1);
}
From there you could do your operation:
y = x | (x - 1)