2012-04-25 4 views

답변

7

Boskop 가장 간단한 방법은 intString을 변환하는 것입니다, 사용 비트 연산 :이 방법에 대해

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); 

그런 다음 String을 검사하여 관심있는 특정 비트를 검사 할 수 있습니다. 하나는 마지막 두 자리 숫자로 표현되는 바이트, 4 개 문자에 고정 된 문자열의 크기를 가정

1

, 그 대답은 할 수있다 :

return (int)hexValue[2] & 1 == 1; 

당신시피, 당신은 필요가 없습니다 5 번째 비트를 평가하기 위해 전체 문자열을 2 진수로 변환하려면 실제로 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); 
} 
관련 문제