Quenyrous
Quenyrous

Reputation: 31

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

I'm writing an x86 assembly program and I want to check a register (it is not 0), to see if more than one bit is on.

Is there a simple way of doing it or should I just loop and shift until I see a 2nd set bit or get to the end?


I don't need the total number of set bits, that would be

Is there something faster than doing one of those and checking for popcnt(x) > 1?

Upvotes: 3

Views: 689

Answers (1)

Aki Suihkonen
Aki Suihkonen

Reputation: 20057

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.

Upvotes: 5

Related Questions