Jordi
Jordi

Reputation: 49

Byte to String in Delphi

I want to convert a Byte to String in Delphi

in c# for example is:

Convert.ToString(Byte, 16);

I tried:

SetString(AnsiStr, PAnsiChar(@ByteArray[0]), LengthOfByteArray);
StringVar := Chr(ByteVar);

Thanks

Upvotes: 0

Views: 6608

Answers (2)

Jordi
Jordi

Reputation: 49

Finally I use this function;

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

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613612

Assuming that Byte is a placeholder for a value of type byte, your C# code converts a single byte to its hexadecimal representation. The Delphi equivalent is IntToHex.

var
  s: string;
  b: Byte;
....
b := ...;
s := IntToHex(b);

Your Delphi code hints at you actually wishing to convert an array of bytes to their hexadecimal representation. In which case the function you need is BinToHex. I can't really give you much more detail because your question itself was lacking in detail. Without knowledge of the types of the variables, we are left making guesses. In future questions, it would be wise to supply a Minimal, Complete, and Verifiable example.

Upvotes: 4

Related Questions