将.net String对象转换为base64编码的字符串
我有一个问题,将 .NET 字符串编码为 base64 时使用哪种 Unicode 编码?我知道字符串在 Windows 上是 UTF-16 编码的,那么我的编码方式是否正确?
public static String ToBase64String(this String source) {
return Convert.ToBase64String(Encoding.Unicode.GetBytes(source));
}
I have a question, which Unicode encoding to use while encoding .NET string into base64? I know strings are UTF-16 encoded on Windows, so is my way of encoding is the right one?
public static String ToBase64String(this String source) {
return Convert.ToBase64String(Encoding.Unicode.GetBytes(source));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您提供的功能非常完善。它将生成以 UTF-16 编码的源字符串字节的 Base64 编码字符串。
如果您询问 UTF-16 是否可以表示字符串中的任何字符,那么可以。 UTF-16 和 UTF-32 之间的唯一区别是 UTF-16 是一种可变长度编码;它使用两个字节来表示子集中的字符,并使用四个字节来表示所有其他字符。
没有任何 unicode 字符不能用 UTF-16 表示。
What you've provided is perfectly functional. It will produce a base64-encoded string of the bytes of your source string encoded in UTF-16.
If you're asking if UTF-16 can represent any character in your string, then yes. The only difference between UTF-16 and UTF-32 is that UTF-16 is a variable-length encoding; it uses two-bytes to represent characters within a subset, and four-bytes for all other characters.
There are no unicode characters that cannot be represented by UTF-16.
请注意,您不必仅仅因为 .NET 字符串使用 UTF-16 就使用 UTF-16。创建该字节数组时,您可以自由选择能够处理字符串中所有字符的任何编码。例如,如果文本采用基于拉丁语的语言,则 UTF-8 会更有效,但它仍然可以处理每个已知字符。
最重要的问题是,无论什么软件解码 Base64 字符串,都需要知道将哪种编码应用于字节数组以重新创建原始字符串。
Be aware that you don't have to use UTF-16 just because that's what .NET strings use. When you create that byte array, you're free to choose any encoding that will handle all the characters in your string. For example, UTF-8 would be more efficient if the text is in a Latin-based language, but it can still handle every known character.
The most important concern is that whatever software decodes the base64 string, needs to know which encoding to apply to the byte array to re-create the original string.
这是解决方案,我已经转换了随机字符串转换,就像您可以给出 Base64 将输出的最大 10 的任何大小。
Here is the Solution, I have converted a Random string conversion like you can give any size up to 10 that Base64 will output.
MSDN 确认 < code>UnicodeEncoding 类表示 Unicode 字符的
UTF-16
编码。MSDN confirms that
UnicodeEncoding
class represents aUTF-16
encoding of Unicode characters.