声明按位运算的掩码
我是这样的低级操作的新手,我希望有人能指出我在这里犯的明显错误。
//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
看起来问题在于掩码的定义方式,但我不知道如何解决它。
I'm new to low level operations like this, I'm hoping someone can point out the obvious mistake I must be making here.
//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
It looks like the problem lies with the way the mask is defined, but I can't see how to fix it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,
0x00001111
是十六进制的,它比255
更大 -16^3 + 16^2 + 16 + 1 = 4369
和字节
溢出。请参阅此处如何表示二进制数或仅使用移位& 15
。First of all
0x00001111
is in hex, which is a larger number than255
-16^3 + 16^2 + 16 + 1 = 4369
andbyte
overflows. Look here how to represent binary numbers or just useshifted & 15
.您的掩码必须是二进制 00001111,等于十六进制 0x0F。
Your mask needs to be binary 00001111, which is equal to hex 0x0F.
使用 java 7,您可以创建二进制文字
0xsomenumbers 是十六进制文字,而 java7 之前的版本不支持二进制文件。
With java 7 you can create binary literals
0xsomenumbers is a hex literal, and pre java7 there is no support for binaries.
你说你想屏蔽前三位,但正如 Petar 所说,0x001111 不是位。如果你想屏蔽这三位,你需要用 7 来屏蔽
You say you want to mask the first three bits but as Petar says, 0x001111 are not bits. If you want to mask the three bits you need to mask with 7