2015-01-21 11 views
0

의 첫 번째 세트 비트의 위치를 ​​얻는 방법, 내 정의처럼 보이는 다음은 숫자, 예를 들어

#define AA    0x0000000000000001LL 
#define BB    0x0000000000000002LL 
#define CC    0x0000000000000004LL 
#define DD    0x0000000000000008LL 
#define EE    0x0000000000000010LL 
#define FF    0x0000000000000020LL 
#define GG    0x0000000000000040LL 
#define HH    0x0000000000000080LL 

내가부터 거꾸로 계산 첫 세트 비트의 위치를 ​​(좀하고 싶습니다 최하위 비트)를 정의합니다.

h = getAmountFromBitwise(HH); 
output of h is 8; 
b = getAmountFromBitwise(BB); 
output b is 2; 

getAmountFromBitwise()를 구현하는 더 좋은 방법이 있습니까?

int getAmountFromBitwise(long long input) { 
    2^x = input; 
    y=x+1; 
    return y; 
} 
+0

무엇보다 나은가요? –

+0

수작업으로 계산하는 것보다 낫습니다. :-D – srjohnhuang

+2

'getAmountFromBitwise()'는 지금 무엇을합니까? – txtechhelp

답변

3

나는 이것을 getAmountFromBitwise()으로 사용합니다.

int highest_bit_set(long long n) { 
    int result = 1; 
    while(n >>= 1) /* keep shifting right until n == 0 */ 
    result++; 
    return result; 
} 

올바른 결과를 얻으려면 n != 0이 필요합니다.