Convert UTF-8 to base64 string

前端 未结 1 986
野趣味
野趣味 2020-12-03 02:14

I\'m trying to convert UTF-8 to base64 string.

Example: I have \"abcdef==\" in UTF-8. It\'s in fact a \"representation\" of a

相关标签:
1条回答
  • 2020-12-03 02:54

    It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

    byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
    string base64 = Convert.ToBase64String(bytes);
    Console.WriteLine(base64);
    

    This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

    Edit:

    To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

    string base64 = "YWJjZGVmPT0=";
    byte[] bytes = Convert.FromBase64String(base64);
    

    At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

    string str = Encoding.UTF8.GetString(bytes);
    Console.WriteLine(str);
    

    This will output the original input string, abcdef== in this case.

    0 讨论(0)
提交回复
热议问题