2013-05-15 142 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

不,对不起,我的错误。在投射时我正在尝试字节而不是(字节)。感谢您的帮助。 –

相关问题