Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - Byte array to string

In my Delphi VCL Form application I've a procedure which has a TBuff parameter (defined before as array of byte). Inside this procedure, I have to convert the parameter to a string.

procedure Form1.Convert(Collect: TBuff);
var 
   str: String;
begin
   str := SysUtils.StringOf(Collect);
end;

After the compile, I was warned about the presence of this compiler error:

Incompatible types :'System.TArray<System.TByte>' and 'TBuff'

like image 518
stacker Avatar asked Feb 05 '14 10:02

stacker


People also ask

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.

How do you create a byte array from a string in Java?

In Java, we can use str. getBytes(StandardCharsets. UTF_8) to convert a String into a byte[] .


1 Answers

The problem that you encounter is that you have defined your own byte array type like this:

type
  TBuff = array of Byte;

This private type of yours is not assignment compatible with other byte array types. Most RTL functions that use byte arrays use the RTL type TBytes which is declared as TArray<Byte>.

The first thing for you to do is to remove TBuff from your program and instead use TBytes. If you continue to use TBuff you will find that all your byte array code lives in its own ghetto, unable to interact with library functionality that uses TBytes. So, escape the ghetto, and remove your TBuff type from existence.

Now, in order to convert a byte array to a string, you need to provide encoding information to do this. You have selected StringOf which should be considered a legacy function these days. It is better to be more explicit in your conversion and use TEncoding.

For instance, if the byte array is UTF-8 you write:

str := TEncoding.UTF8.GetString(ByteArray);

If the byte array is encoded in the local ANSI encoding you write:

str := TEncoding.ANSI.GetString(ByteArray);

In your case the use of StringOf indicates that the byte array is ANSI encoded so this latter example is what you need.

like image 142
David Heffernan Avatar answered Sep 27 '22 22:09

David Heffernan