将UTF-8转换为base64字符串 [英] Convert UTF-8 to base64 string

查看:169
本文介绍了将UTF-8转换为base64字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将 UTF-8 转换为 base64 字符串。



示例:我在 UTF-8 中有abcdef ==。它实际上是一个 base64 字符串的表示。



如何检索abcdef == base64 string(注意我不想要一个 abcdef ==翻译从 UTF-8 ,我想得到一个编码在 base64 的字符串abcdef ==)



编辑由于我的问题似乎不清楚, p>

我的字节数组(让我们命名为A)由一个 base64 字符串表示。转换为 base64 给我abcdef ==



此字符串表示是通过UTF- 8(注意,UTF-8和base64中的字符串表示是完全相同的)。所以我收到一个UTF-8消息,其中包含UTF-8中的whatever / abcdef == / whatever。



所以我需要从这个套接字消息中检索base64abcedf ==字符串,以获得A。



我希望这个更清楚!

解决方案

说出你想要达到的目标有点困难,但是假设您尝试获取一个Base64字符串,当解码 abcdef == 时,以下应该工作:

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

这将输出: YWJjZGVmPT0 =



编辑:



要解码一个Base64字符串,只需使用 Convert.FromBase64String()。例如,

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

此时,字节将成为 byte [] (不是 string )。如果我们知道字节数组表示UTF8中的字符串,则可以使用以下方式将其转换回字符串形式:

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

这将输出原始输入字符串 abcdef == 在这种情况下。


I try to convert UTF-8 to base64 string.

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

How can I retrieve a "abcdef==" base64 string (note that I don't want a "abcdef==" "translation" from UTF-8, I want to get a string encoded in base64 which is "abcdef==")

EDIT As my question seems to be unclear, here is a reformulation :

My byte array (let's say I name it A) is represented by a base64 string. Convert A in base64 gives me "abcdef=="

This string representation is sent through a socket in UTF-8 (note that the string representation is exactly the same in UTF-8 and base64). So I receive an UTF-8 message which contains "whatever/abcdef==/whatever" in UTF-8.

So I need to retrieve the base64 "abcedf==" string from this socket message in order to get A.

I hope this is more clear !

解决方案

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.

这篇关于将UTF-8转换为base64字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆