我有一个帮助函数,它将创建一个密钥或向量字节数组,用于加密方法。不过,我需要一个方法,将采取byte[]
和输出的值以下表示从字节数组string
:如何将字节[]转换为{#,#,#}格式的字符串?
//I need the output to look like this:
"{241, 253, 159, 1, 153, 77, 115, 174, 234, 157, 77, 23, 34, 14, 19, 182, 65, 94, 71, 166, 86, 84, 50, 15, 133, 175, 8, 162, 248, 251, 38, 161}"
我发现这个长手的方法来使用的技术上的作品,但它是一个烂摊子,特别是具有去除最后一个逗号:
public static string ByteArrayToString(byte[] byteArray)
{
var hex = new StringBuilder(byteArray.Length * 2);
foreach (var b in byteArray)
hex.AppendFormat("{0}, ", b);
var output = "{"+ hex.ToString() + "}";
return output.Remove(output.Length - 3, 2); //yuck
}
这似乎是一个非常问的问题,我发现了几个帖子的解决方案,但没有建议输出从byte[]
字符串如我上面所需要的。我检查以下内容:
byte[] to hex string
How do you convert Byte Array to Hexadecimal String, and vice versa?
我使用了几种解析和LINQ例子,但没有它们的输出串中的字节的数组元素作为我上述需要。
有没有办法将我的helpwer方法返回的字节数组的实际值转换为我需要的字符串格式,而不使用方法的黑客?
看起来几乎像JSON。如果您可以将格式更改为真正的JSON(“[1,3,5]”),请考虑使用内置JSON序列化程序或JSON.Net之一。 –
实际上这代表了加密和解密方法中使用的不是JSON的'key'和'iv'值。它已经是'byte []'的形式,所以我需要一种方法来处理它。 – atconway
检出http://msdn.microsoft.com/en-us/library/3a733s97.aspx –