2012-11-12 29 views
4

我有一個uint值,我需要表示爲ByteArray和字符串中的轉換。 當我將字符串轉換回字節數組時,我找到了不同的值。 我使用標準的ASCII轉換器,所以我不明白爲什麼我得到不同的值。 更清楚,這是我在做什麼:C#ByteArray到字符串轉換並返回

byte[] bArray = BitConverter.GetBytes((uint)49694); 
string test = System.Text.Encoding.ASCII.GetString(bArray); 
byte[] result = Encoding.ASCII.GetBytes(test); 

的ByteArray結果是從第一個不同:

bArray - >

[0x00000000]: 0x1e 
[0x00000001]: 0xc2 
[0x00000002]: 0x00 
[0x00000003]: 0x00 

結果 - >

[0x00000000]: 0x1e 
[0x00000001]: 0x3f 
[0x00000002]: 0x00 
[0x00000003]: 0x00 

請注意,兩個數組中的字節1是不同的。

感謝您的支持。

問候

+0

這是問。你搜索過嗎? – nawfal

回答

11
string test = System.Text.Encoding.ASCII.GetString(bArray); 
byte[] result = Encoding.ASCII.GetBytes(test); 

由於原始數據不是ASCIIEncoding.GetString只有意義如果您正在解碼的數據是該編碼中的文本數據。其他任何事情:你腐化它。如果你想存儲一個byte[]作爲string,那麼base-n是必須的 - 通常是base-64,因爲它是方便可用的(Convert.{To|From}Base64String),而b:你可以將它放入ASCII中,所以你很少碰到代碼頁/編碼問題。例如:

byte[] bArray = BitConverter.GetBytes((uint)49694); 
string test = Convert.ToBase64String(bArray); // "HsIAAA==" 
byte[] result = Convert.FromBase64String(test); 
3
Because c2 is not a valid ASCII char and it is replaced with '?'(3f) 

使用SomeEncoding.GetString()不是一個安全的方法,在@activwerx建議註釋轉換任何字節數組的字符串。而是使用Convert.FromBase64StringConvert.ToBase64String

+0

謝謝你的回答。 C1是擴展ASCII中的有效字符。有沒有辦法管理這種情況?提前致謝! – lordpurple

+1

@lordpurple,如果值不是標準的ASCII,你可能想使用不同的編碼,如Encoding.UTF8等 – series0ne

+0

@lordpurple使用SomeEncoding.GetString()將任何*字節數組轉換爲字符串不是一種安全的方法。而是使用'Convert.FromBase64String','Convert.ToBase64String' –

相關問題