0

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

UeliDeSchwert
  • 1,146
  • 10
  • 23
Jordi
  • 49
  • 2
  • 7
  • Possible duplicate of [How to convert strings to array of byte and back](http://stackoverflow.com/questions/21442665/how-to-convert-strings-to-array-of-byte-and-back) – Dinidu Hewage Aug 25 '16 at 07:54

2 Answers2

4

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.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

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;
Jordi
  • 49
  • 2
  • 7
  • This bears little relation to the C# code. It is inelegant with the use of 1 based indexing. It replicates the system function BinToHex. Making a general function be a member of a form class is poor design. In short there is little to commend this to future visitors. – David Heffernan Aug 27 '16 at 07:42