How to convert large UTF-8 strings into ASCII?

前端 未结 9 1755
盖世英雄少女心
盖世英雄少女心 2020-12-18 08:29

I need to convert large UTF-8 strings into ASCII. It should be reversible, and ideally a quick/lightweight algorithm.

How can I do this? I need the source

9条回答
  •  被撕碎了的回忆
    2020-12-18 08:57

    If the string is encoded as UTF-8, it's not a string any more. It's binary data, and if you want to represent the binary data as ASCII, you have to format it into a string that can be represented using the limited ASCII character set.

    One way is to use base-64 encoding (example in C#):

    string original = "asdf";
    // encode the string into UTF-8 data:
    byte[] encodedUtf8 = Encoding.UTF8.GetBytes(original);
    // format the data into base-64:
    string base64 = Convert.ToBase64String(encodedUtf8);
    

    If you want the string encoded as ASCII data:

    // encode the base-64 string into ASCII data:
    byte[] encodedAscii = Encoding.ASCII.GetBytes(base64);
    

提交回复
热议问题