bitcount函數統計其整數參數的值爲1的二進制位的個數

/* bitcount:  count 1 bits in x */
int bitcount(unsigned x)
{
    int b;
 
    for (b = 0; x != 0; x >>= 1)
        if (x & 01)
            b++;
    return b;
}


然後升級版本:

根據:表達式 x & =(x - 1) 可以刪除x中最右邊值爲1的一個二進制位

解釋:

Answer: If x is odd, then (x-1) has the same bit representation as x except that the rightmost 1-bit is now a 0. In this case, (x & (x-1)) == (x-1). If x is even, then the representation of (x-1) has the rightmost zeros of x becoming ones and the rightmost one becoming a zero. Anding the two clears the rightmost 1-bit in x and all the rightmost 1-bits from (x-1).

所以升級後:

/* bitcount:  count 1 bits in x */
int bitcount(unsigned x)
{
    int b;
 
    for (b = 0; x != 0; x &= (x-1))
        b++;
    return b;
} 
加快了執行速度

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章