我知道这个问题在堆栈溢出之前被问了两次,但这次我要求最有保证的方式(不改变数据值的方式)。我想从字符串转换为字节[]然后回到字符串。我可以用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'](https://msdn.microsoft.com/en-us/library/system.convert.tobase64string(v = vs.110) ).aspx)会给你一个比上面列出的所有项目更短的字符串。 –
另外,什么问题“[如何将字节数组转换为十六进制字符串,反之亦然?](http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to - 十六进制字符串 - 反之亦然)“不适合你? –