Thursday, June 23, 2011

Neat x86 trick

While these days it's becoming more and more of a forgotten art, bit wizardry and size coding is a fascinating subject. Many such tricks are known, and published over the decades in venues ranging from HAKMEM, to several books, to the venerable Art of Computer Programming.

In this post I show one such trick I didn't find anywhere else (although I didn't look that hard). Suppose you want to increment and decrement integers with a defined floor and ceiling; let us call those f and c. We can avoid branching by doing

sub eax, c
adc eax, c

to increment, and

sub eax, f+1
adc eax, f

to decrement. You can see that, by making clever use of the carry flag, one avoids both extra registers (as with, e.g., cmov) and branching.