As stated above, using mov
and and
are the quickest solutions here, but the fun part about programming is that one can find many solutions to a single problem, so as a less efficient alternative, you could use one of the following codes.
So you can also solve it like this:
xor ebx, ebx ; sets ebx = 0
TEST eax, 1 ; is the lowest bit set?
JZ skip_add ; if low bit is zero, skip next instruction
; if lowest bit was set / AND op resulted not zero
add ebx, 1 ; ebx += 1, or use `INC ebx`
skip_add:
; process the result
Alternatively, you can also use:
xor ebx, ebx ; ebx = 0
shr eax, 1 ; shift right: lowest bit in carry flag now
adc ebx, 0 ; ebx += 0 + carry bit
shl eax, 1 ; get back original value of eax, `shl` and `or` with ebx
or eax, ebx ; or use `push eax` and `pop eax` instead
Another alternative (similar to the other answers, but more costy):
push eax
and eax, 1
xchg ebx, eax ; swap contents, could also use `mov` here
pop eax
Note that both solutions do not change the value in eax
, so you can still use the value in eax freely. Also note that the commented values are for eax
having the value of 3 as mov eax, 3
was used in the question.
If you already know, that ebx
is zero, you can skip the xor
lines and if changing eax
doesn't matter, you can just delete the shl
operation as well. So the actual operation is done by about two instructions, as you can see. About the µops, see the comment of Peter, though.