boskop
boskop

Reputation: 619

How to check if bit is set in Hex-String?

shifters...

I've to do something, that twist my mind.

I'm getting a hex value as String (for example: "AFFE") and have to decide, if bit 5 of Byte one is set.

public boolean isBitSet(String hexValue) {
    //enter your code here
    return "no idea".equals("no idea")
}

Any hints?

Regards,

Boskop

Upvotes: 3

Views: 4703

Answers (4)

dao hodac
dao hodac

Reputation: 371

Use the BigInteger and it's testBit built-in function

static public boolean getBit(String hex, int bit) {
    BigInteger bigInteger = new BigInteger(hex, 16);
    return bigInteger.testBit(bit);
}

Upvotes: 0

user694833
user694833

Reputation:

Assuming that byte one is represented by the last two digits, and the size of the string fixed to 4 characters, then the answer may be:

return (int)hexValue[2] & 1 == 1;

As you an see, you don't need to convert the whole string to binary to evaluate the 5th bit, it is indeed the LSB of the 3rd character.

Now, if the size of the hex string is variable, then you will need something like:

return (int)hexValue[hexValue.Length-2] & 1 == 1;

But as the string can have a length smaller than 2, it would be safer:

return hexValue.Length < 2 ? 0 : (int)hexValue[hexValue.Length-2] & 1 == 1;

The correct answer may vary depending on what you consider to be byte 1 and bit 5.

Upvotes: 1

dbyrne
dbyrne

Reputation: 61011

How about this?

 int x = Integer.parseInt(hexValue);
 String binaryValue = Integer.toBinaryString(x);

Then you can examine the String to check the particular bits you care about.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The simplest way is to convert String to int, and use bit arithmetic:

public boolean isBitSet(String hexValue, int bitNumber) {
    int val = Integer.valueOf(hexValue, 16);
    return (val & (1 << bitNumber)) != 0;
}               ^     ^--- int value with only the target bit set to one
                |--------- bit-wise "AND"

Upvotes: 8

Related Questions