2012-04-25 35 views
3

移位器...如何檢查位是否設置爲十六進制字符串?

我必須做些事情,那扭轉我的想法。

我得到一個十六進制值作爲字符串(例如:「AFFE」),並且必須決定是否設置了字節1的位5。

public boolean isBitSet(String hexValue) { 
    //enter your code here 
    return "no idea".equals("no idea") 
} 

任何提示?

問候,

Boskop

回答

7

最簡單的方法是將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" 
0

這個怎麼樣?

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; 

正確的答案可能取決於你認爲什麼是字節1,位變化5.

0

使用BigInteger和它的testBit內置功能

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