2013-05-15 145 views
0

我有一個字節00111101.我想將它分成兩部分,如0011 1101,並創建兩個新字節00000011和00001101.我怎樣才能在Java中完成它?將一個字節分成幾部分

我的代碼是:

byte b; //b has a particular value 
byte result1= (b>>4) && 0x0f; 
byte result2= b & 0x0f; 

此代碼是給我下面的錯誤:

cannot convert from int to byte. 

回答

5

你只需要添加一個投:

byte result1= (byte) ((b>>4) && 0x0f); 
byte result2= (byte) (b & 0x0f); 

運算的結果對小於int的整數類型的操作隱式提升爲int,所以你必須把它扔回byte

JLS 5.6.2指定此行爲的二進制數值提升規則的一部分:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

If either operand is of type double, the other is converted to double.

Otherwise, if either operand is of type float, the other is converted to float.

Otherwise, if either operand is of type long, the other is converted to long.

Otherwise, both operands are converted to type int.

+0

哎呦,固定。抱歉。 –

+0

當我試圖將其轉換回字節時,它說「刪除令牌字節」。 –

+0

不,對不起,我的錯誤。在投射時我正在嘗試字節而不是(字節)。感謝您的幫助。 –

相關問題