Search code examples
freepascallazarus

delphi/Lazarus/pascal , how to conver integer to byte array ?


I use Lazarus , but less document , I want convert integer to byte array , Distinguish between big-endian and small-endian.

for example i is 1 I want convert to byte array 00,00,00,01 and 01,00,00,00 big and small .


Solution

  • Only for CPUs that are Little-Endian:

    FUNCTION BigEndian(V : UInt32) : TBytes;
      VAR
        I : Int32;
       
      BEGIN
        SetLength(Result,4);
        FOR I:=LOW(Result) TO HIGH(Result) DO BEGIN
          Result[I]:=(V AND $FF000000) SHR 24;
          V:=(V AND $00FFFFFF) SHL 8
        END
      END;
    
    FUNCTION LittleEndian(V : UInt32) : TBytes;
      VAR
        I : Int32;
       
      BEGIN
        SetLength(Result,4);
        FOR I:=LOW(Result) TO HIGH(Result) DO BEGIN
          Result[I]:=V AND $000000FF;
          V:=V SHR 8
        END
      END;
    

    Another option for LittleEndian (again - on Little-Endian CPUs):

    FUNCTION LittleEndian(V : UInt32) : TBytes;
      BEGIN
        SetLength(Result,4);
        MOVE(V,Result[0],4)
      END;
    

    Don't know enough about Lazarus to know if it compiles unmodified there, but the above compiles fine in Delphi.

    Endian-agnostic versions:

    FUNCTION BigEndian(V : UInt32) : TBytes;
      VAR
        I : Int32;
    
      BEGIN
        SetLength(Result,4);
        FOR I:=HIGH(Result) DOWNTO LOW(Result) DO BEGIN
          Result[I]:=V MOD 256;
          V:=V DIV 256
        END
      END;
    
    FUNCTION SmallEndian(V : UInt32) : TBytes;
      VAR
        I : Int32;
    
      BEGIN
        SetLength(Result,4);
        FOR I:=LOW(Result) TO HIGH(Result) DO BEGIN
          Result[I]:=V MOD 256;
          V:=V DIV 256
        END
      END;