Search code examples
delphibytereverseendianness

Swapping order of bytes in Delphi


I'm not very familiar with arrays of bite and big/little endians but I need to write an integer value into byte array in reverse and I don't know how to do it in Delphi code. C# has BitConverter.Reverse methong which is so much easier, is there any equivalent for it in Delphi? This is my code so far:

x := 1500977838953;
setLength(byteArray, 8);
Move(x, byteArray[2], SizeOf(x));
showMessage(ByteToHex(byteArray));

ByteToHex is a method that returns me hex string so I can read the bytes if they are in correct order. The result that I am getting is : 0000693B40795D01 but I need it to be: 00-00-01-5D-79-40-3B-69

Any ideas how I can achieve this?

Edit:

function ByteToHex(b: array of byte): String;
const HexSymbols = '0123456789ABCDEF';
var i: integer;
begin
  SetLength(Result, 2*Length(b));
  for i :=  0 to Length(b)-1 do begin
    Result[1 + 2*i + 0] := HexSymbols[1 + b[i] shr 4];
    Result[1 + 2*i + 1] := HexSymbols[1 + b[i] and $0F];
  end;
end;

Solution

  • Here is an example how to use the ReverseBytes() procedure:

    program Project20;
    {$APPTYPE CONSOLE}
    uses
      System.SysUtils;
    
    procedure ReverseBytes(Source, Dest: Pointer; Size: Integer);
    begin
      Dest := PByte(NativeUInt(Dest) + Size - 1);
      while (Size > 0) do
      begin
        PByte(Dest)^ := PByte(Source)^;
        Inc(PByte(Source));
        Dec(PByte(Dest));
        Dec(Size);
      end;
    end;
    
    var x,y : Int64;
    
    begin
      x := 1500977838953;
      WriteLn(x);
      ReverseBytes(Addr(x),Addr(y),SizeOf(x)); // Or ReverseBytes(@x,@y,SizeOf(x));
      WriteLn(IntToHex(x));
      WriteLn(IntToHex(y));
      ReadLn;
    end.
    

    Output:

    1500977838953
    0000015D79403B69
    693B40795D010000
    

    To get the address of a variable, use the Addr() function or the @ operator. The result is a 64-bit integer with all bytes in reversed order, as shown by the output.

    There are other ways to swap the byte order of a variable. Search for bswap for example.