2013-07-12 72 views
1

我有一个帮助函数,它将创建一个密钥或向量字节数组,用于加密方法。不过,我需要一个方法,将采取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方法返回的字节数组的实际值转换为我需要的字符串格式,而不使用方法的黑客?

+0

看起来几乎像JSON。如果您可以将格式更改为真正的JSON(“[1,3,5]”),请考虑使用内置JSON序列化程序或JSON.Net之一。 –

+0

实际上这代表了加密和解密方法中使用的不是JSON的'key'和'iv'值。它已经是'byte []'的形式,所以我需要一种方法来处理它。 – atconway

+0

检出http://msdn.microsoft.com/en-us/library/3a733s97.aspx –

回答

4

非常方便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) + ";"; 
+0

这是*正是*我正在寻找这个问题。不错的工作! – atconway

+0

所以我可以替换下列内容:'private byte [] defaultVector = {146,64,191,111,23,3,113,119,231,121,252,112,79,32,114,156};'与'私人字节[] defaultVector = mJhaxtPOq + DqHvO9 + QmR2oSlAKzna68L04BEeKL4u7Y ='我不认为后者将工作,因为我键入它,虽然? – atconway

+2

如果意图是编写C#代码,漂亮的打印解决方案可能是最好的。要以这种方式使用base64编码的字符串,你应该执行private byte [] defaultVector = Convert。FromBase64String(“mJhaxtPOq + DqHvO9 + QmR2oSlAKzna68L04BEeKL4u7Y =”);'但是这使得它必须在运行时解析字符串 - 并不像编译器知道的那样好。 –

相关问题