2017-02-13 53 views
0

這是我的問題:我需要將字節數組轉換爲int,在xamarin pcl上。 但我有tryed這一點:將字節數組轉換爲xamarin pcl c中的int#

byte[] fromBoardSerial = new byte[3]; 
fromBoardSerial[0] = 0x04 
fromBoardSerial[1] = 0x93 
fromBoardSerial[2] = 0xe0 

result = BitConverter.ToInt32(fromBoardSerial, 0); 

解決方案

Array.Reverse(fromBoardSerial); //call before conversion 

結果是:-527236096 ... ..而是正確的結果應該是:300000 如何從int中的數組字節進行轉換?

感謝

+0

一定有什麼東西錯一個整數由4個字節? – NtFreX

+0

是的是正確的...如果你會嘗試它:http://www.binaryhexconverter.com/hex-to-decimal-converter –

回答

1

看起來你這裏有兩個問題:

  1. 的字節數。您必須有4個字節才能轉換爲Int32。
  2. 字節順序。它看起來像你試圖計算你的數字「倒退」。

看看這段代碼:

byte[] fromBoardSerial = new byte[4]; 
fromBoardSerial[0] = 0xe0; 
fromBoardSerial[1] = 0x93; 
fromBoardSerial[2] = 0x04; 
fromBoardSerial[3] = 0x00; 

var result = BitConverter.ToInt32(fromBoardSerial, 0); // result = 300000 
+0

我解決了這個:Array.Reverse(fromBoardSerial);和位轉換後...如果你更新答案我檢查正確的答案 –