How to check if more than one bit is set in x86 assembly?

Viewed 120
1 Answers

As almost commented by ecm, one can check if a value is a power of two by checking

a) value != 0 &&
b) ((value - 1) & value) == 0

However, if one needs to check if a value has more than 1 bit, it is enough to test that

c) ((value - 1) & value) != 0

lea  ebx, [eax - 1]
test eax, ebx ;  // Z flag is cleared on EAX having 2 or more bits

That is: if a value is non-zero after some bit (that was originally set) has been cleared, it must have had more than 1 bit set.

BMI1 extension has a single instruction: clear least significant bit blsr, which also sets the ZF accordingly.

Related