Here's another method that takes advantage of a short circuit with logical AND operations and conditional commands or an instruction pipeline.
unsigned int value;
unsigned int temp_value = value;
bool bit_found = false;
unsigned int index = 0;
bit_found = !bit_found && ((temp_value & (1 << index++));
bit_found = !bit_found && ((temp_value & (1 << index++));
bit_found = !bit_found && ((temp_value & (1 << index++));
bit_found = !bit_found && ((temp_value & (1 << index++));
bit_found = !bit_found && ((temp_value & (1 << index++));
return index - 1;
The advantage of this method is that there are no branches, and the command pipeline is not broken. It is very fast on processors that execute conditional execution of instructions.
source
share