How To Find The Leading Number Of Zero's In a Number using C

后端 未结 6 2109
星月不相逢
星月不相逢 2021-02-04 21:07

for example,if i have number 64,then its binary representation would be 0000 0000 0000 0000 0000 0000 0100 0000 so leading number of zero\'s is 25. remember i have to calculate

6条回答
  •  死守一世寂寞
    2021-02-04 21:16

    I would go with:

    unsigned long clz(unsigned long n) {
        unsigned long result = 0;
        unsigned long mask = 0;
        mask = ~mask;
        auto size = sizeof(n) * 8;
        auto shift = size / 2;
        mask >>= shift;
        while (shift >= 1) {
            if (n <= mask) {
                result += shift;
                n <<= shift;
            }
            shift /= 2;
            mask <<= shift;
        }
        return result;
    }
    

提交回复
热议问题