Declaring masks for bitwise operations

北城余情 提交于 2019-12-07 05:45:49

问题


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.


回答1:


Your mask needs to be binary 00001111, which is equal to hex 0x0F.

byte mask = (byte)0x0F;



回答2:


First of all 0x00001111 is in hex, which is a larger number than 255 - 16^3 + 16^2 + 16 + 1 = 4369 and byte overflows. Look here how to represent binary numbers or just use shifted & 15.




回答3:


With java 7 you can create binary literals

byte binaryLit = (byte)0b00001111;

0xsomenumbers is a hex literal, and pre java7 there is no support for binaries.




回答4:


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



来源:https://stackoverflow.com/questions/8124165/declaring-masks-for-bitwise-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!