2014-03-01 100 views
0

我不知道爲什麼,但是當你做的下一件事,你永遠不會得到相同的原始字節數組:獲取從字節數組字符數組,然後返回字節數組

var b = new byte[] {252, 2, 56, 8, 9}; 
var g = System.Text.Encoding.ASCII.GetChars(b); 
var f = System.Text.Encoding.ASCII.GetBytes(g); 

如果你願意運行這段代碼你會看到b!= f,爲什麼? 有什麼辦法將字節轉換爲字符,然後回到字節,並得到原始字節數組相同?

+5

因爲'252'不能用作ASCII字符(它是7位)。所以在任何任意字節數組和字符串之間進行轉換可能是有損的。 –

+0

你想用字符做什麼? –

+0

@ L.B我如何解決它? –

回答

2

byte value can be 0 to 255

當字節值> 127,然後導致的

System.Text.Encoding.ASCII.GetChars() 

總是'?'具有價值

因此,

System.Text.Encoding.ASCII.GetBytes() 

結果總是爲那些(錯誤值)有起始字節值> 127


如果您需要TABLE ASCII -II然後你可以做如下

 var b = new byte[] { 252, 2, 56, 8, 9 }; 
     //another encoding 
     var e = Encoding.GetEncoding("437"); 
     //252 inside the mentioned table is ⁿ and now you have it 
     var g = e.GetString(b); 
     //now you can get the byte value 252 
     var f = e.GetBytes(g); 

類似的帖子,你可以閱讀

How to convert the byte 255 to a signed char in C#

How can I convert extended ascii to a System.String?

-2

唯一的區別是第一個字節:252.因爲ascii字符是1字節的有符號字符,它的取值範圍是-128到127.實際上你的輸入是不正確的。 signed char不能爲252.

+0

http://en.wikipedia。org/wiki/ASCII –

+0

我並不是在談論真正的ascii。我在談論代碼中的ascii。我故意寫這種方式很容易理解。我知道沒有什麼叫ascii無符號字符。 –

+0

ascii沒有負值。 –

0

爲什麼不使用字符?

var b = new byte[] {252, 2, 56, 8, 9}; 
var g = new char[b.Length]; 
var f = new byte[g.Length]; // can also be b.Length, doens't really matter 
for (int i = 0; i < b.Length; i++) 
{ 
    g[i] = Convert.ToChar(b[i]); 
} 
for (int i = 0; i < f.Length; i++) 
{ 
    f[i] = Convert.ToByte(g[i]); 
}