byte[] 和 string 之间转换的最佳方式?
Best way of converting between byte[] and string?
我知道这个问题之前在stack-overflow上被问过两次,但这次我问的是最有保障的方式(不改变数据值的方式)。我想从字符串转换为 byte[],然后再转换回字符串。我可以使用 ByteConverter
、Convert
、Encoding
、BitConverter
、HttpServerUtility.UrlTokenEncode / HttpServerUtility.UrlTokenDecode
以下代码:
string s2 = BitConverter.ToString(bytes); // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
{
decBytes2[i] = Convert.ToByte(tempAry[i], 16);
}
或以下代码:
private string ToString(byte[] bytes)
{
string response = string.Empty;
foreach (byte b in bytes)
response += (Char)b;
return response;
}
如果你仍然没有得到我想要的,我想知道哪种方式有效,哪种方式无效,我想知道应该使用哪种方式。嘿,我更喜欢大小最小的字节数组,因为我将通过网络发送这个数组,并且我将使用前 256 个字节。
I want to convert from string to byte[] then back to string.
如果这就是您真正想要做的,您只需在接收方使用 Encoding.UTF8.GetBytes(string)
on the sending side and Encoding.UTF8.GetString(byte[])
。
private byte[] ToBytes(string message)
{
return Encoding.UTF8.GetBytes(message);
}
private string ToString(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
这将使您能够以最少的字节数将任何字符串转换为字节并再次转换回字符串。
这将 NOT 将 byte[] 转换为 string 到 byte[],对于这样的事情你需要使用一些东西喜欢 Convert.ToBase64String(byte[])
and Convert.FromBase64String(string)
。在格式不正确的 UTF8 字符串上使用 Encoding.UTF8.GetString(byte[])
可能会导致您在转换过程中丢失数据。
我知道这个问题之前在stack-overflow上被问过两次,但这次我问的是最有保障的方式(不改变数据值的方式)。我想从字符串转换为 byte[],然后再转换回字符串。我可以使用 ByteConverter
、Convert
、Encoding
、BitConverter
、HttpServerUtility.UrlTokenEncode / HttpServerUtility.UrlTokenDecode
以下代码:
string s2 = BitConverter.ToString(bytes); // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
{
decBytes2[i] = Convert.ToByte(tempAry[i], 16);
}
或以下代码:
private string ToString(byte[] bytes)
{
string response = string.Empty;
foreach (byte b in bytes)
response += (Char)b;
return response;
}
如果你仍然没有得到我想要的,我想知道哪种方式有效,哪种方式无效,我想知道应该使用哪种方式。嘿,我更喜欢大小最小的字节数组,因为我将通过网络发送这个数组,并且我将使用前 256 个字节。
I want to convert from string to byte[] then back to string.
如果这就是您真正想要做的,您只需在接收方使用 Encoding.UTF8.GetBytes(string)
on the sending side and Encoding.UTF8.GetString(byte[])
。
private byte[] ToBytes(string message)
{
return Encoding.UTF8.GetBytes(message);
}
private string ToString(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
这将使您能够以最少的字节数将任何字符串转换为字节并再次转换回字符串。
这将 NOT 将 byte[] 转换为 string 到 byte[],对于这样的事情你需要使用一些东西喜欢 Convert.ToBase64String(byte[])
and Convert.FromBase64String(string)
。在格式不正确的 UTF8 字符串上使用 Encoding.UTF8.GetString(byte[])
可能会导致您在转换过程中丢失数据。