I have a value DB of 3 bytes (DB_1, DB_2, DB_3).
I need to check DB_3 for specific bits. For example I have to see if
DB_3 == 11X0XXXX
Where only bit 4, 6 and 7 should be checked. Bits marked as X can take any value and should not be checked. I am not familiar with Bit operations in Java and glad for any help!
Thanks!
I have a value DB of 3 bytes (DB_1, DB_2, DB_3). I need to
Share
You can use a bitwise AND (
&in Java) to accomplish the masking to specific bits (the mask is the second line and will only let those bits of the first line through where the mask has a1[marked with arrows below the calculation]):You’ll retain exactly those bits that were
1in both operands, so essentially you set all those bits to0that you are not interested in.So you just need to do
0xD0is the hexadecimal form of208which is11010000in binary and you want to know whether it matches0xC0which is192, or11000000. You’ll know that all the bits you don’t care about (theXes in your question) are already zero at this point due to the bitwise AND.ETA (2011-12-14 14:24): Apparently Java 7 has binary integer literals, so you can do
which makes the mask more readily apparent. Thanks, Glenn.