Java bit inspection

Hello,

I need a sanity check here...
Lets say II have a hexadecimal String of "D410" and I'm inspecting byte 1.  bits 1-4 is the lower nibble "4" and bits 5-8 is the upper nibble "D".  

1.  The most significant byte is 0 and the most significant bit is bit 7.  What exactly does that mean?
2.  If I had a requirement to get byte 1, bit 3's value (0 or 1), what is the best way to accomplish this?

I would attempt to do this using the following methodology:

-for bit 3 I would look at the "4" from the hex String of "D410" and parse that to an Integer with a radius of 16 and then call the readBit method passing it the bit location of 3.  I'm unsure if passing readBit the value 3 is the proper parameter?

//get the value of bit 3 of byte 1 of the below hex String
String hex="D410";
readBit(Integer.parseInt(hex.substring(1,2), 16), 3);

 public int readBit(Integer i, int bit) {
        int binaryValue = 0;
        if (i != null) {
            if ((i & (1 << bit)) != 0) {
                binaryValue = 1;
            }
        }
        return binaryValue;
    }


cgray1223Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
CEHJConnect With a Mentor Commented:
>>2.  If I had a requirement to get byte 1, bit 3's value (0 or 1), what is the best way to accomplish this?

There's a little confusion here: 1 is the higher *nybble* and 0 the lower.

    public static int getNybble(int bite, boolean higher) {
	int shift = higher? 4 : 0;
	return (bite >> shift) & 0x0F;
    }

Open in new window

0
 
cmalakarCommented:
>> I'm unsure if passing readBit the value 3 is the proper parameter?

If you want to get the value @ that bit position, then you need that value right.
0
 
sailingbyeCommented:
It looks good to me.

A couple of minor comments though; the method Integer.parseInt(String, int) returns a simple int therefore your Integer parameter, i, will cause some unnecessary boxing of an int to an Integer, and readBit could be more concise. I tested the following code with apparent success.

Hope this helps.

int readBit (int i, int bit) {
  bit = 1 << bit;
  return ((i & bit) == bit ? 1 : 0);
}

Open in new window

0
 
CEHJCommented:
Of course you could render that as the following too
    public static int getNybble(int bite, boolean higher) {
        return higher? (bite >> 4) & 0x0F : bite & 0xF;
    }

Open in new window

0
 
CEHJCommented:
:-)
0
All Courses

From novice to tech pro — start learning today.