C# 如何安全地将字节数组转换为字符串并返回?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1134671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I safely convert a byte array into a string and back?
提问by Svish
I don't really care about encoding and stuff, as long as I get back the exact same byte array.
我真的不关心编码和东西,只要我得到完全相同的字节数组。
So to sum up: How do I convert a byte array into a string, and then that string back into the same byte array I started with?
总结一下:如何将字节数组转换为字符串,然后将该字符串转换回我开始使用的同一个字节数组?
采纳答案by Jon Skeet
The absolute safest way to convert bytes to a string and back is to use base64:
将字节转换为字符串并返回的绝对最安全的方法是使用 base64:
string base64 = Convert.ToBase64String(bytes);
byte[] bytes = Convert.FromBase64String(base64);
That way you're guaranteed not to get "invalid" unicode sequences such as the first half of a surrogate pair without the second half. Nothing's going to decide to normalize the data into something strange (it's all ASCII). There's no chance of using code points which aren't registered in Unicode, or anything like that. Oh, and you can cut and paste without much fear, too.
这样你就可以保证不会得到“无效”的 unicode 序列,比如没有后半部分的代理对的前半部分。没有什么会决定将数据规范化为奇怪的东西(都是 ASCII)。没有机会使用未在 Unicode 中注册的代码点或类似的东西。哦,你也可以毫不畏惧地剪切和粘贴。
Yes, you end up with 4 characters for every 3 bytes - but that's a small price to pay for the knowledge that your data won't be corrupted.
是的,您最终每 3 个字节有 4 个字符 - 但对于知道您的数据不会被破坏的知识来说,这是一个很小的代价。
回答by Aragorn
You can use Convert.ToBase64 documentation http://msdn.microsoft.com/en-us/library/dhx0d524.aspx
您可以使用 Convert.ToBase64 文档http://msdn.microsoft.com/en-us/library/dhx0d524.aspx
回答by Ricky G
You can just use the Convert
class as below.
你可以只使用Convert
下面的类。
/// <summary>
/// Converts a string to byte array
/// </summary>
/// <param name="input">The string</param>
/// <returns>The byte array</returns>
public static byte[] ConvertToByteArray(string input)
{
return input.Select(Convert.ToByte).ToArray();
}
/// <summary>
/// Converts a byte array to a string
/// </summary>
/// <param name="bytes">the byte array</param>
/// <returns>The string</returns>
public static string ConvertToString(byte[] bytes)
{
return new string(bytes.Select(Convert.ToChar).ToArray());
}
/// <summary>
/// Converts a byte array to a string
/// </summary>
/// <param name="bytes">the byte array</param>
/// <returns>The string</returns>
public static string ConvertToBase64String(byte[] bytes)
{
return Convert.ToBase64String(bytes);
}