FILESTREAM字节未正确编写
为什么使用RAD Studio 10.1中的以下代码获得错误的输出?
var
sPalette : string;
mystream: TfileStream;
begin
mystream := TfileStream.Create('C:\Data\test.bmp', fmCreate);
sPalette := #1#2#3#4#5#6;
mystream.WriteBuffer(Pointer(sPalette)^, Length(sPalette));
mystream.Free;
end;
获得输出:01 00 02 00 03 00
预期输出:01 02 03 04 05 06
Why do I get the wrong output using the following code in RAD Studio 10.1?
var
sPalette : string;
mystream: TfileStream;
begin
mystream := TfileStream.Create('C:\Data\test.bmp', fmCreate);
sPalette := #1#2#3#4#5#6;
mystream.WriteBuffer(Pointer(sPalette)^, Length(sPalette));
mystream.Free;
end;
Got Output : 01 00 02 00 03 00
Expected output : 01 02 03 04 05 06
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在Delphi 2009+中,
String
是16位,UTF-16编码Unicodestring
。您没有考虑到sizeof(char)
是2个字节,而不是您期望的1个字节。长度(String)
以字符数量表示,而不是字节数。您的字符串长度为6个字符,但大小为12个字节。您仅将字符串
的第一个字节写入文件。而且,由于您的字符串
包含下面的ASCII字符#128
,因此每个其他字节都是$ 00
。使用8位
ansistring
,例如:或者,使用
tencoding
将Unicode字符串转换为8位字节编码:或者:另外:
不过,您真的不应该是首先使用
字符串
作为二进制数据。例如,使用字节数组,例如:或者更好,只需使用
tbitmap
对象,因为您正在写入.bmp
文件,例如:In Delphi 2009+,
string
is a 16-bit, UTF-16 encodedUnicodeString
. You are not taking into account thatSizeOf(Char)
is 2 bytes, not 1 byte as you are expecting.Length(string)
is expressed in number of characters, not in number of bytes. Your string is 6 characters in length, but is 12 bytes in size. You are writing only the 1st 6 bytes of thestring
to your file. And since yourstring
contains ASCII characters below#128
, every other byte will be$00
.Use an 8-bit
AnsiString
instead, eg:Or, use
TEncoding
to convert the Unicode string to an 8-bit byte encoding:Alternatively:
Though, you really should not be using a
string
for binary data in the first place. Use a byte array instead, eg:Or better, just use a
TBitmap
object, since you are writing to a.bmp
file, eg: