Java 声明按位操作的掩码

Java 声明按位操作的掩码,java,bit-manipulation,bitmask,Java,Bit Manipulation,Bitmask,我对这种低级操作还不熟悉,我希望有人能指出我在这里犯的明显错误 //Input value - 00111100 //I want to get the value of the bits at indexes 1-3 i.e 0111. byte mask = (byte)0x00001111; // This gives 17 not the 15 I'd expect byte shifted = (byte)(headerByte >> 3); //shifted is

我对这种低级操作还不熟悉,我希望有人能指出我在这里犯的明显错误

//Input value - 00111100
//I want to get the value of the bits at indexes 1-3 i.e 0111.

byte mask = (byte)0x00001111; // This gives 17 not the 15 I'd expect 

byte shifted = (byte)(headerByte >> 3);
//shifted is 7 as expected

byte frameSizeValue = (byte)(shifted & mask); //Gives 1 not 7

看起来问题在于掩码的定义方式,但我看不出如何修复它。

首先
0x00001111
是十六进制的,它比
255
-
16^3+16^2+16+1=4399
byte
溢出的数字大。看看如何表示二进制数,或者只使用移位&15

你说你想屏蔽前三位,但正如Petar所说,0x001111不是位。如果您想屏蔽需要用7屏蔽的三位,那么您的屏蔽需要是二进制00001111,它等于十六进制0x0F

byte mask = (byte)0x0F;

使用Java7,您可以创建二进制文本

byte binaryLit = (byte)0b00001111;

0xsomenumbers是十六进制文字,在java7之前不支持二进制文件。

谢谢,正如Justin所示,我将二进制文件误解为十六进制。谢谢你的链接。很酷,我实际上是在用J2ME。不过进步不错。