TEncoding & TNetEncoding(使用現成的TBase64Encoding,TEncoding和TMBCSEncoding)

來源:互聯網
上載者:User

標籤:

TEncoding and TNetEncoding are abstract classes and you will never instantiate one of them, because only the descendants will have the full functionality. Normally you would need to write something like this...

Code:
var  Encoding: TEncoding  Buffer: TArray<Byte>;begin  Encoding := TMBCSEncoding.Create(GetACP, 0, 0);  try    Buffer := Encoding.GetBytes(‘Hello world!‘);    (...)  finally    Encoding.Free();  end;end;

...and you get the ANSI values for "Hello world!". But this isn‘t really funny and bloates the code, therefore often used Encodings like ASCII, ANSI, UTF8 and other are implemented as Singleton. Therefore the using is normally something like this...

Code:
var  Buffer: TArray<Byte>;begin  Buffer := TEncoding.ANSI.GetBytes(‘Hello world!‘);  (...)end;

In this case the RTL holds and manages an instance of an ANSI encoding object and you will always get the same object. Now sometimes it‘s needed to work with other code pages and for this cases the function "GetEncoding(...)" exists. You will use it in this way...

Code:
var  Encoding: TEncoding;  Buffer: TArray<Byte>;begin  Encoding := TEncoding.GetEncoding(852);  try    Buffer := Encoding.GetBytes(‘Hello‘);    (...)  finally    Encoding.Free();  <- must have  end;end;

Note: You need to destroy such instances by your own. In case you use often the same code page, just use a global variable, otherwise use it like any other class too.


The class TNetEncoding has the same schema as TEncoding is using. It is an abstract class which offers with the properties Base64, HTML and URL certain encoder. Even the class TBase64Encoding has an overloaded constructor, which allows to tweak the output. In the example below is the "LineSeparator" empty and therefore the output has not line breaks, which is far away from what default behaviour offers.

Code:
class function TEncodingUtils.BytesToBase64(Buffer: PByte; const Offset, Count: Integer): string;var  Encoder: TBase64Encoding;  Input: PByte;begin  Encoder := TBase64Encoding.Create(MaxInt, ‘‘);  try    Input := Buffer;    Inc(Input, Offset);    Result := Encoder.EncodeBytesToString(Input, Count);  finally    Encoder.Free();  end;end;

https://www.board4allcz.eu/showthread.php?t=634856

TEncoding & TNetEncoding(使用現成的TBase64Encoding,TEncoding和TMBCSEncoding)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.