Java 如何检查位是否设置为十六进制字符串?

Java 如何检查位是否设置为十六进制字符串?,java,hex,bit-manipulation,Java,Hex,Bit Manipulation,移位器 我得做点什么,让我心烦意乱 我得到一个十六进制值作为字符串(例如:“aff”),并且必须决定是否设置了字节1的第5位 public boolean isBitSet(String hexValue) { //enter your code here return "no idea".equals("no idea") } 有什么提示吗 问候, Boskop最简单的方法是将字符串转换为int,并使用位算术: public boolean isBitSet(String h

移位器

我得做点什么,让我心烦意乱

我得到一个十六进制值作为字符串(例如:“aff”),并且必须决定是否设置了字节1的第5位

public boolean isBitSet(String hexValue) {
    //enter your code here
    return "no idea".equals("no idea")
}
有什么提示吗

问候,


Boskop

最简单的方法是将
字符串
转换为
int
,并使用位算术:

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"
public boolean isBitSet(字符串hexValue,int位号){
int val=Integer.valueOf(hexValue,16);
return(val&(1这个怎么样

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

然后,您可以检查字符串以检查您关心的特定位。

假设字节1由最后两位数字表示,并且字符串的大小固定为4个字符,则答案可能是:

return (int)hexValue[2] & 1 == 1;
如您所见,您不需要将整个字符串转换为二进制来计算第5位,它实际上是第3个字符的LSB

现在,如果十六进制字符串的大小是可变的,那么您将需要如下内容:

return (int)hexValue[hexValue.Length-2] & 1 == 1;
但由于字符串的长度可以小于2,因此更安全:

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

正确答案可能根据您认为字节1和位5的不同而有所不同。

< P>使用BigTimes和它的测试位内置函数

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