Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 244
boskop Avatar asked Jan 19 '26 21:01

boskop


1 Answers

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"
like image 168
Sergey Kalinichenko Avatar answered Jan 21 '26 20:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!