Search code examples
delphiassemblybasm

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;

Solution

  • 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;