boskop boskop - 6 days ago 6
Java Question

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

Answer

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"
Comments