11 Vote

Delphi/Lazarus: Show Byte Array as String of HEX Values

Tip by Delphian | Last update on 2021-04-02 | Created on 2018-01-01

When working with Byte Arrays sooner or later the question of visualization raises. Here it makes sense to output the individual bytes in hexadecimal form as a string. In this tip, I want to show you a function that does just that.

In the example we are using the following definition of a byte array:

type
  TByteArr = array of Byte;

The function goes through the byte array byte by byte and converts each byte value into the corresponding hexadecimal value:

function ByteArrayToHexString(BA: TByteArr; Sep: string = ''): string;
var
  i, k: integer;
begin
  result:='';

  if Sep='' then begin
     for i:=low(BA) to high(BA) do 
       result := result + IntToHex(BA[i], 2);
  end else begin
     k:=high(BA);
     for i:=low(BA) to k do begin
        result:= result + IntToHex(BA[i], 2);
        if k<>i then result := result + Sep;
     end;
  end;
end; 

On the one hand, the function can be called only with a byte array or on the other hand optionally with a separator, which is written between the individual bytes for better readability.

var
  BA: TByteArr;
  s: string;
begin
  SetLength(BA, 3);
  BA[0] := 65;
  BA[1] := $41;
  BA[2] := %1000001; // this only works in Lazarus

  s := ByteArrayToHexString(BA);        // 414141
  s := ByteArrayToHexString(BA, ' ');   // 41 41 41

In this example, we first create a byte array that is 3 bytes long and then fill it with some values. Then we use our function to output these values.

Load and Save Byte Array

In this context, it is also interesting how to load or save a byte array from respectively to a file.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Save Binary Data as String

Question | 1 Answer

PHP: Show content of array

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.