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

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

问题描述

我正在尝试将 UTF-8 转换为 base64 字符串.

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

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

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

如何检索abcdef=="base64 字符串(请注意,我不想要来自 UTF-8 的abcdef=="翻译",我想得到一个以 base64 编码的字符串,它abcdef==").

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:

我的字节数组(假设我将其命名为 A)由一个 base64 字符串表示.将 A 转换为 base64 给我abcdef==".

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

这个字符串表示是通过 UTF-8 的套接字发送的(注意字符串表示在 UTF-8 和 base64 中是完全相同的).所以我收到一条 UTF-8 消息,其中包含 UTF-8 中的whatever/abcdef==/whatever".

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.

所以我需要从这个套接字消息中检索 base64 "abcedf==" 字符串才能得到 A.

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

我希望这更清楚!

推荐答案

很难说你想要实现什么,但假设你试图获得一个 Base64 字符串,解码em> 是 abcdef==,以下应该可以工作:

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);

这将输出:YWJjZGVmPT0= 这是 abcdef== 以 Base64 编码的.

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

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

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

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

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

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);

这将输出原始输入字符串,在本例中为 abcdef==.

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

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

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