Wednesday, August 31, 2016

80x86 snippets

Here are some branchless routines in 80x86 assembly:

Here is a simple routine to get the absolute difference between AL & BL
AL, DL destroyed, absolute difference in AL
sub al, bl ; AL to BL ; positive difference negative differencesbb dl, dl ; DL=0  DL=-1 xor al, dl ; AL xor 0 = AL AL xor -1 = not ALsub al, dl ; AL - 0 = AL not AL --1 = neg AL

Instead of sbb, one can also use cbw (sign extend AL into AH), cwd (sign extend AX into DX) and cdq (sign extend EAX into EDX). See below:
cdq ; sign extend EAX into EDX ( = -1 if EAX negative)
xor eax, edx
sub eax, edx
The last 2 lines can also be re-arranged so:
cdq
add eax, edx
xor eax, edx

 For maximum of 2 numbers, one can use
; AL = max(AH, AL)  ; AL > AH AL < AH
sub ah, al ; AH = AH - AL
cmc
sbb dl, dl ; DL = 0 DL = AH - AL
and dl, ah
add al, dl ; AL = AL AL = AL + AH - AL
For minimum of 2 numbers, one can use
sub     ebx,eax
sbb     edx,edx
and     edx,ebx
add     eax,edx