シフター...
私は何かをしなければなりません、それは私の心をねじります。
文字列として16進値(例: "AFFE")を取得しており、バイト1のビット5が設定されているかどうかを判断する必要があります。
public boolean isBitSet(String hexValue) {
//enter your code here
return "no idea".equals("no idea")
}
ヒントはありますか?
よろしく、
ボスコップ
シフター...
私は何かをしなければなりません、それは私の心をねじります。
文字列として16進値(例: "AFFE")を取得しており、バイト1のビット5が設定されているかどうかを判断する必要があります。
public boolean isBitSet(String hexValue) {
//enter your code here
return "no idea".equals("no idea")
}
ヒントはありますか?
よろしく、
ボスコップ
最も簡単な方法は、に変換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"
バイト1が最後の2桁で表され、文字列のサイズが4文字に固定されているとすると、答えは次のようになります。
return (int)hexValue[2] & 1 == 1;
ご覧のとおり、5番目のビットを評価するために文字列全体をバイナリに変換する必要はありません。実際には3番目の文字のLSBです。
ここで、16進文字列のサイズが可変の場合、次のようなものが必要になります。
return (int)hexValue[hexValue.Length-2] & 1 == 1;
ただし、文字列の長さは2未満にすることができるため、より安全です。
return hexValue.Length < 2 ? 0 : (int)hexValue[hexValue.Length-2] & 1 == 1;
正解は、バイト1とビット5と見なすものによって異なる場合があります。
これはどう?
int x = Integer.parseInt(hexValue);
String binaryValue = Integer.toBinaryString(x);
次に、文字列を調べて、気になる特定のビットを確認できます。
BigIntegerとそのtestBit組み込み関数を使用します
static public boolean getBit(String hex, int bit) {
BigInteger bigInteger = new BigInteger(hex, 16);
return bigInteger.testBit(bit);
}