Do you consider using the Swap compiler function?
procedure TForm1.FormCreate(Sender: TObject); var a: word; begin a := $1234; a := Swap(a); Caption := IntToHex(a, 4) end;
If not, you don't need ASM for this (and ASM probably won't be available in 64-bit Delphi). You can just do
procedure MySwap(var a: word); var tmp: byte; begin tmp := PByte(@a)^; PByte(@a)^ := PByte(NativeUInt(@a) + sizeof(byte))^; PByte(NativeUInt(@a) + sizeof(byte))^ := tmp; end; procedure TForm1.FormCreate(Sender: TObject); var a: word; begin a := $123456; MySwap(a); Caption := IntToHex(a, 4) end;
and, of course, there are a million variants of this topic.
procedure MySwap(var a: word); var tmp: byte; type PWordRec = ^TWordRec; TWordRec = packed record byte1, byte2: byte; end; begin with PWordRec(@a)^ do begin tmp := byte1; byte1 := byte2; byte2 := tmp; end; end;
and, very briefly,
procedure MySwap(var a: word); begin a := word(a shl 8) + byte(a shr 8); end;
or
procedure MySwap(var a: word); begin a := lo(a) shl 8 + hi(a); end;
Andreas Rejbrand
source share