I'm (still) making my way through some of the bit hacks, and doing it all in assembly, for example from a previous question, Check if a number is even.
Here is what I have for toggling a bit:
toggle_bit:
# NUM XOR (1 <<POS), pos is 1-indexed
# Note:
# NUM xor 0 = NUM
# NUM xor 1 = not(NUM), i.e., flip all bits
mov $1, %eax # the bit to shift (pos-1)
lea -1(%esi), %ecx # shift amount -- pos-1
shl %cl, %rax # now we have the 1 at the correct bit position
xor %rdi, %rax
ret
And called as:
mov $0b101, %edi # (5)
mov $2, %esi # (toggle 2nd bit)
call toggle_bit # return 0b111 (7)
Is this the suggested way to toggle a bit? Or should I be using the btc
instruction?
Update: here is my improved function using btc
:
toggle_bit:
mov %rdi, %rax # move the num into the return register
dec %sil # so pos it's one-indexed
btc %rsi, %rax
ret
It's one instruction shorter than the first way -- is one way 'better' than the other. If so, why?