2015-01-21 59 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

比什么好? – 2015-01-21 08:34:27

+0

比手动计数好。 :-D – srjohnhuang 2015-01-21 08:35:39

+2

getAmountFromBitwise()现在做什么? – txtechhelp 2015-01-21 08:36:52

回答

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为正确的结果。