声明位运算掩码

5

我对低级操作这样的东西还是很陌生的,希望有人能指出我在这里可能犯的明显错误。

//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

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

4个回答

7

首先,0x00001111 是十六进制,比 255 大,即 16^3 + 16^2 + 16 + 1 = 4369,所以会导致 byte 溢出。请参考这里了解如何表示二进制数,或者直接使用 shifted & 15


谢谢,正如Justin所示,我将二进制误解为十六进制。感谢提供链接。 - Tristan Warner-Smith

5

您的面具需要是二进制00001111,它等于十六进制0x0F。

byte mask = (byte)0x0F;

4

使用Java 7,您可以创建二进制字面量

byte binaryLit = (byte)0b00001111;

0xsomenumbers是十六进制字面量,在Java7之前不支持二进制。


很酷,我正在使用J2ME。不过还是有很大的改进空间。 - Tristan Warner-Smith

0

你说你想要屏蔽前三位,但正如Petar所说,0x001111不是位。如果你想要屏蔽三位,你需要用7来进行屏蔽。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接