我有我使用的東西轉換像一個文本框:將字節從文本框轉換爲字節數組到字符時出現奇怪的行爲?
74 00 65 00 73 00 74 00
回字符串,上面寫着「測試」,但由於某種原因,當我點擊轉換按鈕,將顯示只有第一個字母「 t「74 00
和其他字節數組正如預期的那樣工作,整個文本被轉換。
這裏是2碼我試圖其產生的整個字節數組不能正確轉換回字相同的行爲:
byte[] bArray = ByteStrToByteArray(iSequence.Text);
ASCIIEncoding enc = new ASCIIEncoding();
string word = enc.GetString(bArray);
iResult.Text = word + Environment.NewLine;
它使用該函數:
private byte[] ByteStrToByteArray(string byteString)
{
byteString = byteString.Replace(" ", string.Empty);
byte[] buffer = new byte[byteString.Length/2];
for (int i = 0; i < byteString.Length; i += 2)
buffer[i/2] = (byte)Convert.ToByte(byteString.Substring(i, 2), 16);
return buffer;
}
另一種方式我正在使用的是:
string str = iSequence.Text.Replace(" ", "");
byte[] bArray = Enumerable.Range(0, str.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(str.Substring(x, 2), 16))
.ToArray();
ASCIIEncoding enc = new ASCIIEncoding();
string word = enc.GetString(bArray);
iResult.Text = word + Environment.NewLine;
嘗試檢查的長度,看看它是否iteratrat通過和它是...
不知道如何調試爲什麼這是發生在上述字節數組,但所有其他字節數組似乎工作得很好只有這一個只輸出第一個字母的。
我做了什麼錯誤,可能會產生這種行爲一些如何? 我可以嘗試什麼以找出哪些問題?
感謝了很多解釋什麼,我試圖做的,爲什麼它不能正常工作。 – Prix 2011-06-01 03:32:23