Reputation: 15010
I have a String
object in Delphi. I want to convert that to TByteDynArray
. I have tried the implementation below.But while debugging I find that binaryData
is empty after the assignment.What am I doing wrong?
procedure convertStringToTByteDynArray;
var
binaryData:TByteDynArray;
Data: String;
begin
Data := '8080100B1D472';
//Copy over string to TByteDynArray
SetLength(binaryData,Length(Data));
Move(Data[1],binaryData,Length(Data));
end
Upvotes: 0
Views: 4819
Reputation: 26401
The size of Char
is 1 byte in Delphi 2007 and earlier, but is 2 bytes in Delphi 2009 and later. In the latter case, the code will put UTF-16 data into the bytearray, but will only copy half of the characters.
The core mistake you are making is that passing binarydata
by itself to Move()
passes the memory location of the variable itself, which is just a pointer to other memory. Passing binarydata[0]
instead passes the memory location of the first element of the allocated memory that the TByteDynArray
is pointing at. That is what you need to pass instead.
I also added a Length()
check that avoids some rangecheck errors when those are enabled.
procedure convertStringToTByteDynArray;
var
binaryData: TByteDynArray;
Data: String;
begin
Data := '8080100B1D472';
//Copy over string to TByteDynArray
SetLength(binaryData, Length(Data) * sizeof(Char));
if Length(Data) > 0 then
Move(Data[1], binaryData[0], Length(Data) * sizeof(Char));
end;
Alternatively:
procedure convertStringToTByteDynArray;
var
binaryData: TByteDynArray;
Data: String;
begin
Data := '8080100B1D472';
//Copy over string to TByteDynArray
SetLength(binaryData, Length(Data) * sizeof(Char));
Move(PChar(Data)^, PByte(binaryData)^, Length(binaryData));
end;
Upvotes: 4