zoukankan      html  css  js  c++  java
  • TEncoding & TNetEncoding(使用现成的TBase64Encoding,TEncoding和TMBCSEncoding)

    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

  • 相关阅读:
    关于 CommonJS AMD CMD UMD 规范
    如何成为一名卓越的前端工程师
    javascript 中 void 0的含义及undefine于void 0区别
    原生js获取样式表:currentStyle与defaultView的区别 真实例子
    attachEvent与addEventListener的区别 真实例子
    将图片转换成黑白(灰色、置灰)
    前端图片缓存问题
    html里的<wbr>标签什么意思
    关于SQL SERVER中的FLOAT转换为VARCHAR
    记一次工作需求: RSA密钥之C#格式与Java格式转换
  • 原文地址:https://www.cnblogs.com/findumars/p/5745256.html
Copyright © 2011-2022 走看看