boskop boskop - 8 months ago 46
Java Question

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


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?



Answer Source

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"