移位器...如何检查位是否设置为十六进制字符串?
我必须做些事情,那扭转我的想法。
我得到一个十六进制值作为字符串(例如:“AFFE”),并且必须决定是否设置了字节1的位5。
public boolean isBitSet(String hexValue) {
//enter your code here
return "no idea".equals("no idea")
}
任何提示?
问候,
Boskop
移位器...如何检查位是否设置为十六进制字符串?
我必须做些事情,那扭转我的想法。
我得到一个十六进制值作为字符串(例如:“AFFE”),并且必须决定是否设置了字节1的位5。
public boolean isBitSet(String hexValue) {
//enter your code here
return "no idea".equals("no idea")
}
任何提示?
问候,
Boskop
最简单的方法是将String
转换为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"
这个怎么样?
int x = Integer.parseInt(hexValue);
String binaryValue = Integer.toBinaryString(x);
然后你可以检查字符串来检查你关心的特定位。
假设一个字节由最后两位数字来表示,并固定为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;
正确的答案可能取决于你认为什么是字节1,位变化5.
使用BigInteger和它的testBit内置功能
static public boolean getBit(String hex, int bit) {
BigInteger bigInteger = new BigInteger(hex, 16);
return bigInteger.testBit(bit);
}