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
In Delphi 2009+,
stringis 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 thestringto your file. And since yourstringcontains ASCII characters below#128, every other byte will be$00.Use an 8-bit
AnsiStringinstead, eg:Or, use
TEncodingto convert the Unicode string to an 8-bit byte encoding:Alternatively:
Though, you really should not be using a
stringfor binary data in the first place. Use a byte array instead, eg:Or better, just use a
TBitmapobject, since you are writing to a.bmpfile, eg: