将字符串转换为TByteDynArray [英] Converting String to TByteDynArray
问题描述
我在Delphi中有一个 String
对象.我想将其转换为 TByteDynArray
.我已经在下面尝试了实现,但是在调试时发现 binaryData
为空,我在做什么错了?
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
推荐答案
在Delphi 2007及更早版本中, Char
的大小为1个字节,而在Delphi 2009及更高版本中为2个字节.在后一种情况下,代码会将UTF-16数据放入字节数组,但仅复制一半字符.
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.
您正在犯的核心错误是将 binarydata
本身传递给 Move()
会传递变量本身的存储位置,这只是指向其他内存的指针.相反,传递 binarydata [0]
会传递 TByteDynArray
指向的已分配内存的第一个元素的存储位置.那就是您需要通过的内容.
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.
我还添加了一个 Length()
检查,该检查可以避免在启用范围检查时出现一些错误.
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;
或者:
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;
这篇关于将字符串转换为TByteDynArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!