Is power of two — BMI1 version

Author:Wojciech Muła
Added on:2018-03-11

To check if a number is a power of two, the instruction BLSR from BMI1 extension can be used. The instruction resets the least set bit of a number, i.e. calculates (x - 1) and x. A sample C procedure that use the bit-trick:

bool is_power_of_two(int x) {
    return (x != 0) && (x == ((x - 1) & x));

If a number has exactly one bit set then BLSR yields zero. However, when input of BLSR is zero, the instruction also yields zero. Fortunately, BLSR sets CPU flags in following way:

Thanks to that we can properly handle all cases. Below is an assembly code:

blsr %eax, %eax

// result = (ZF == 1) and (CF == 0)
setz %al                // al = ZF
sbb  $0, %al            // al = ZF - CF
movzx %al, %eax         // cast

Sample program is available.