【问题标题】:Convert 1 character as 1 byte in Delphi 2010在 Delphi 2010 中将 1 个字符转换为 1 个字节
【发布时间】:2016-07-27 10:38:26
【问题描述】:

我知道在 Delphi 7 中,AnsiString 类型为 1 个字节,但在 Delphi 2010 中,UnicodeString 类型为 2 个字节。

以下代码适用于 Delphi 7

var
    FS: TFileStream;
    BinarySize: integer;
    FreeAvailable, TotalSpace: int64;
    fname: string;
    StringAsBytes: array of Byte;
begin
    ..............
    FS := TFileStream.Create(drive+'\'+fname+'.BIN', fmOpenReadWrite or fmShareDenyWrite);
    try
        BinarySize := (Length(fname) + 1) * SizeOf(Char);
        SetLength(StringAsBytes, BinarySize);
        Move(fname[1], StringAsBytes[0], BinarySize);

        FS.Position:=172903;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
        FS.Position:=173111;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
        FS.Position:=173235;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
        FS.Position:=173683;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
        FS.Position:=173695;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
    finally
        FS.Free;
    end;
end;

但它不适用于 Delphi 2010。请帮助!

【问题讨论】:

标签: arrays string delphi


【解决方案1】:

如果您不需要支持 Unicode-Chars,我会对其进行更改,使其明确使用 AnsiChar / AnsiString:

var
    FS: TFileStream;
    BinarySize: integer;
    FreeAvailable, TotalSpace: int64;
    fname: AnsiString;
    StringAsBytes: array of Byte;
begin
    ..............
    FS := TFileStream.Create(drive+'\'+fname+'.BIN', fmOpenReadWrite or fmShareDenyWrite);
    try
        BinarySize := (Length(fname) + 1) * SizeOf(AnsiChar);
        SetLength(StringAsBytes, BinarySize);
        Move(fname[1], StringAsBytes[0], BinarySize);

        FS.Position:=172903;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
        FS.Position:=173111;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
        FS.Position:=173235;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
        FS.Position:=173683;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
        FS.Position:=173695;
        FS.WriteBuffer(StringAsBytes[0], Length(StringAsBytes));
    finally
        FS.Free;
    end;
end;

【讨论】:

  • 这行不通,Length(StringAsBytes) = Length(fname) + 1
  • @nguyentu:如果 StringAsBytes 预期为空终止,它将起作用。 +1 为空终止符保留空间,SetLength() 零初始化缓冲存储器,Move() 不会覆盖保留的终止符。
  • 无论如何,StringAsBytes 是多余的,可以删除。 AnsiString 可以直接传递给WriteBuffer() 例如:FS.WriteBuffer(PAnsiChar(fname)^, Length(fname));,或者如果您需要编写空终止符:FS.WriteBuffer(PAnsiChar(fname)^, Length(fname)+1);
猜你喜欢
  • 2012-05-25
  • 2022-11-28
  • 2013-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
相关资源
最近更新 更多