int a = 12;
for eg: binary of 12 is 1100 so answer should be 3 as 3rd bit from right is set.
I want the position of the last most set bit o
You must check all 32 bits starting at index 0 and working your way to the left. If you can bitwise-and your a
with a one bit at that position and get a non-zero value back, it means the bit is set.
#include
int last_set_pos(int a) {
for (int i = 0; i < sizeof a * CHAR_BIT; ++i) {
if (a & (0x1 << i)) return i;
}
return -1; // a == 0
}
On typical systems int will be 32 bits, but doing sizeof a * CHAR_BIT
will get you the right number of bits in a
even if it's a different size