Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

procedure that swaps the bytes (low/high) of a Word variable

I have this procedure that swaps the bytes (low/high) of a Word variable (It does the same stuff as System.Swap function). The procedure works when the compiler optimization is OFF but not when it is ON. Can anybody help me with this?

procedure SwapWord(VAR TwoBytes: word);   
asm
  Mov EBX, TwoBytes
  Mov AX, [EBX]
  XCHG AL,AH
  Mov [EBX], AX
end;
like image 422
Server Overflow Avatar asked Feb 27 '11 15:02

Server Overflow


1 Answers

Fastest:

function ReverseWord(w: word): word;
asm
   {$IFDEF CPUX64}
   mov rax, rcx
   {$ENDIF}
   xchg   al, ah
end;

In case you want to reverse DWORD too:

function ReverseDWord(dw: cardinal): cardinal;
asm
  {$IFDEF CPUX64}
  mov rax, rcx
  {$ENDIF}
  bswap eax
end;
like image 54
gabr Avatar answered Nov 16 '22 02:11

gabr