-1

Is there any builtin function in C that returns me the first bit equals to zero in a 32-bit integer?

I know I can check all 32-bit using a for-loop:

value <--- parameter (uint32_t)
for (int i=0; i<32; i++){
  uint32_t pos = 1 << i;
  if (pos ^ value) return i;  // xor
}
return -1;
Guilherme
  • 443
  • 5
  • 22

1 Answers1

2

Unfortunately there's no standardized C function to do this, but many C compilers offer one of their own. When you use GCC it's the _builtin_ctz function. When you use Microsoft Visual C it's the _BitScanForward function.

If you want to write programs that compile on multiple different compilers then you end up using a lot of #ifdef statements to provide the same thing in different ways. (I keep hoping the C committee will mandate one of them already!)

librik
  • 3,738
  • 1
  • 19
  • 20