2016-07-27 104 views
-2

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

下面的代码是运作良好的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; 

,但它并不适用于2010年德尔福工作,请帮帮忙!

+2

你知道为什么它不工作。那里有这么多的资源。你有没有努力去理解这个? –

+0

http://docwiki.embarcadero.com/VCL/2010/en/SysUtils.TEncoding.GetBytes和http://docwiki.embarcadero.com/VCL/2010/en/SysUtils.TEncoding_Properties –

+0

我也有使用'StringAsBytes := TEncoding.ASCII.GetBytes(fname);'我检查了十六进制代码,一切正常,但事实上,这是不正确 – nguyentu

回答

0

如果您不需要支持Unicode的字符数,我会使其明确使用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; 
+0

这不起作用,'Length (StringAsBytes)= Length(fname)+ 1' – nguyentu

+0

@nguyentu:如果'StringAsBytes'预计为空终止,它将工作。 +1为空终止符保留空间,'SetLength()'零初始化缓冲区内存,'Move()'不覆盖保留的终止符。 –

+1

无论如何,'StringAsBytes'是多余的,可以删除。 'AnsiString'可以直接传递给'WriteBuffer()'例如:'FS.WriteBuffer(PAnsiChar(fname)^,Length(fname));',或者你需要写空终止符:'FS .WriteBuffer(PAnsiChar(fname)^,Length(fname)+1);' –

相关问题