delphidelphi-2009

how to convert byte array to its hex representation in Delphi


I have TBytes variable with a value [0,0,15,15]. How can I convert it to "00FF" ?

I dont want to use loops, bcoz this logic to be used in time intensive function.

(I tried using BinToHex, but I could not get it working with string variable.)

Thanks & Regards,

Pavan.


Solution

  • // Swapping is necessary because x86 is little-endian.
    function Swap32(value: Integer): Integer;
    asm
      bswap eax
    end;
    
    function FourBytesToHex(const bytes: TBytes): string;
    var
      IntBytes: PInteger;
      FullResult: string;
    begin
      Assert(Length(bytes) = SizeOf(IntBytes^));
      IntBytes := PInteger(bytes);
      FullResult := IntToHex(Swap32(IntBytes^), 8);
      Result := FullResult[2] + FullResult[4] + FullResult[6] + FullResult[8];
    end;
    

    If that last line looks a little strange, it's because you requested a four-byte array be turned into a four-character string, whereas in the general case, eight hexadecimal digits are required to represent a four-byte value. I'm simply assumed that your byte values are all below 16, so only one hexadecimal digit is needed. If your example was a typo, then simply replace the last two lines with this one:

    Result := IntToHex(Swap32(IntBytes^), 8);
    

    By the way, your requirement forbidding loops will not be met. IntToHex uses a loop internally.