Reputation: 9827
If I have a hex value of 53, what is the best way in Java to see what the values of bit 6 and bit 7 are? Bit 1 will be considered as the Least Significant Bit (or the rightmost bit within a byte).
The goal is to take bit6 and bit7 and convert them to its combined decimal form.
Upvotes: 0
Views: 368
Reputation: 68907
That is easy:
byte b = 53;
boolean bit6 = ((b >> 5) & 1) == 1;
boolean bit7 = ((b >> 6) & 1) == 1;
Or:
byte b = 53;
int bit6and7 = b & (0x3 << 5); // Will give: 0 bit7 bit6 0 0 0 0 0
Or:
byte b = 53;
int bit6and7 = (b >> 5) & 0x3; // Will give: 0 0 0 0 0 0 bit7 bit6
Upvotes: 1
Reputation: 234867
The easiest way, I think is:
int bits7And8 = (byteValue >>> 5) & 3;
That will give you bits 6 and 7 in the lowest two bit positions. If you need their value as a String
:
String bits7And8String = Integer.toString(bits7And8);
Upvotes: 2