我有一个辅助函数,可以创建用于加密方法的 key 或向量字节数组。但是,我需要一种方法,它将采用 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 示例,但它们都没有按照我上面的需要输出字符串中的字节数组元素。
有没有一种方法可以将我的帮助方法返回的字节数组的实际值转换为我需要的字符串格式,而无需使用该方法的 hack?
请您参考如下方法:
非常方便string.Join是您想要的关键。
public static string ByteArrayToString(byte[] byteArray)
{
return "{" + string.Join(", ", byteArray) + "}";
}
如果您正在为计算机编码,而不是为了向人类漂亮地打印出来,base64可能是对这些字节进行编码的更好方法。它允许更紧凑的编码。例如。这段代码:
public static string ByteArrayToString(byte[] byteArray)
{
return Convert.ToBase64String(byteArray);
}
生成 44 个字符的 8f2fAZlNc67qnU0XIg4TtkFeR6ZWVDIPha8Iovj7JqE= 而不是您为这 32 个字节提供的 142 个字符的字符串。转换回 byte[] 只是 Convert.FromBase64String(theString),而不必自己拆分和解析长字符串。
更新:这里有一个用于生成紧凑代码的选项:
public static string ByteArrayEncoded(byte[] byteArray)
{
return "Convert.FromBase64String(\""+Convert.ToBase64String(byteArray)+"\")";
}
像这样使用:
string generatedLine = "private static readonly byte[] defaultVector = "
+ ByteArrayEncoded(myArray) + ";";
