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

werewolves ...

I have to do something, it twists my mind.

I get the hexadecimal value as a String (for example: "AFFE") and have to decide if the 5 byte bit will be set.

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

Any clues?

Yours faithfully,

Boskop

+3
source share
4 answers

The easiest way is to convert Stringto intand 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"
+7
source

Assuming the byte is represented by the last two digits, and the line size is fixed at 4 characters, then the answer could be:

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

As you can see, you do not need to convert the entire string to binary in order to evaluate the 5th bit, it is really the LSB of the third character.

, , - :

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

2, :

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

, 1 5.

+1

How about this?

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

You can then check the String to check the specific bits you care about.

0
source

Use BigInteger and the built-in testBit function

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

All Articles