0

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.

3
  • You can mask each bit with the corresponding power of 2 number. For example, to know the value of the fourth bit you would use bitwise and with 8. x & 8 => x & (2^3) Commented Jan 8, 2013 at 21:21
  • 2
    The usual bit addressing is that the least significant bit is bit 0, not bit 1. Commented Jan 8, 2013 at 21:24
  • While not a direct answer to your question, you may also be interested in Integer.toBinaryString(int) Commented Jan 8, 2013 at 21:30

2 Answers 2

2

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); 
Sign up to request clarification or add additional context in comments.

3 Comments

@c12 - Sorry - I was off by one because of your unconventional indexing of the least significant bit being 1 instead of 0.
byte byteValue = 53; is that what you intended for your example? assuming a hex of 53.
@c12 - If the hex value is 53 (binary 01010011), then bits 7 and 8 (6 and 7 in your indexing scheme) are binary 10, which is 2 in decimal. That's what I understood you to want. (The "7And8" in the variable names should be "6And7" to be consistent with your indexing scheme.)
1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.