2017-07-25 18 views
3

我在需要轉換爲整數的二進制文件中讀取3個字節。整數轉換中的字節移位問題

我使用此代碼讀取字節:

LastNum last1Hz = new LastNum(); 
last1Hz.Freq = 1; 
Byte[] LastNumBytes1Hz = new Byte[3]; 
Array.Copy(lap_info, (8 + (32 * k)), LastNumBytes1Hz, 0, 3); 
last1Hz.NumData = LastNumBytes1Hz[2] << 16 + LastNumBytes1Hz[1] << 8 + LastNumBytes1Hz[0]; 

last1Hz.NumDatainteger

這似乎是在我看到的帖子中將bytes轉換爲integers的好方法。

這裏是值的捕獲閱讀:

enter image description here

但整數last1Hz.NumData始終爲0

我失去了一些東西,但無法弄清楚什麼。

+1

加法具有比位移更高的優先級。 – Luaan

+0

是的,現在好了,謝謝。 – Alexus

回答

4

您需要使用括號(因爲除了具有比位移位更高的優先級):

int a = 0x87; 
int b = 0x00; 
int c = 0x00; 

int x = c << 16 + b << 8 + a; // result 0 
int z = (c << 16) + (b << 8) + a; // result 135 

您的代碼應該是這樣的:

last1Hz.NumData = (LastNumBytes1Hz[2] << 16) + (LastNumBytes1Hz[1] << 8) + LastNumBytes1Hz[0]; 
+0

是的,謝謝你的回答,它現在正在工作。 – Alexus

0

我認爲這個問題是一個數量級優先問題。前< < 穿戴括號中以強制位移位被首先計算+進行評價。

last1Hz.NumData = (LastNumBytes1Hz[2] << 16) + (LastNumBytes1Hz[1] << 8) + LastNumBytes1Hz[0];