I’m writing a function, which determine the number of useful bits of a 16 bits integer.
int16_t
f(int16_t x)
{
/* ... */
}
For example, the number “00000010 00100101” has 10 useful bits. I think I should use some bitwise operators, but I don’t know how. I’m looking for some ways to do it.
If you’re using gcc (or a gcc-compatible compiler such as ICC) then you can use built in intrinsics, e.g.
This assumes you just want the number of bits to the right of the last leading zero bit.
For MSVC you can use
_BitScanReversewith some adjustment.Otherwise if you need this to be portable then you can implement your own general purpose
clzfunction, see e.g. http://en.wikipedia.org/wiki/Find_first_set