【发布时间】:2016-07-19 19:28:11
【问题描述】:
我知道这个问题之前在 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 个字节。
【问题讨论】:
-
如果您想要使用最少数据量的
Convert.ToBase64String会给您一个比您上面列出的所有项目短得多的字符串。
标签: c# type-conversion byte bytearray