2013-07-12 74 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 =」);'但是這使得它必須在運行時解析字符串 - 並不像編譯器知道的那樣好。 –

相關問題