1

你能告诉我我该怎么做吗?是否有任何 Freepascal 单元可以为我做到这一点?我需要它,这样我的程序才能以基于 XML 的文件格式存储二进制数据。

4

1 回答 1

9

使用base64单位和它的两个类,TBase64EncodingStreamTBase64DecodingStream

这是一个简单的例子

program demo;

uses Classes, base64;

var
  DecodedStream: TStringStream;
  EncodedStream: TStringStream;
  Encoder: TBase64EncodingStream;
  Output: string;
begin
  DecodedStream := TStringStream.Create('Hello World!');
  EncodedStream := TStringStream.Create('');
  Encoder       := TBase64EncodingStream.Create(EncodedStream);
  Encoder.CopyFrom(DecodedStream, DecodedStream.Size);

  Output := EncodedStream.DataString;
  { Outputs 'SGVsbG8gV29ybGQh' }
  WriteLn(Output);

  DecodedStream.Free;
  EncodedStream.Free;
  Encoder.Free;
end.

并且,在相反的方向

program demo;

uses Classes, base64;

var
  DecodedStream: TStringStream;
  EncodedStream: TStringStream;
  Decoder: TBase64DecodingStream;
  Output: string;
begin
  EncodedStream := TStringStream.Create('SGVsbG8gV29ybGQh');
  DecodedStream := TStringStream.Create('');
  Decoder       := TBase64DecodingStream.Create(EncodedStream);
  DecodedStream.CopyFrom(Decoder, Decoder.Size);

  Output := DecodedStream.DataString;
  { Outputs 'Hello World!' }
  WriteLn(Output);

  DecodedStream.Free;
  EncodedStream.Free;
  Decoder.Free;
end.

或用于非基于流的使用的简写encodestringbase64decodestringbase64 (2.4.4+):

Uses Base64;
var 
   s : AnsiString;
Begin
  s:=EncodeStringBase64('Hello world!');
  Writeln('Encoded : ',s);
  s:=DecodeStringBase64(s);
  Writeln('Decoded again : ',s);    
end.
于 2012-04-20T08:21:17.437 回答