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:

boolis_power_of_two(intx){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:

ZF is set when result is zero,

CF is set when input is zero (note that if CF is set, ZF is also set).

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