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 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
};
// range : [0, 32]
inline int flagCount(unsigned n){
return flagtable[n & 0xff] + flagtable[(n >> 8) & 0xff] + flagtable[(n >> 16) & 0xff] + flagtable[(n >> 24) & 0xff];
}
// range : [0, 32]
int highContinuousFlagCount(unsigned n){
while ((n & (n + (n & ~(n - 1)))) != 0)
n &= n - 1;
return flagCount(n);
}
// range : [0, 32], index started with 1
int lowFlagIndex(unsigned n){
if (0 == n)
return 0;
int offset = 0;
while (((n >> offset) & 255) == 0)
offset += 8;
return lowflagtable[(n >> offset) & 255] + offset;
}
// range : [0, 32], index started with 1
int highFlagIndex(unsigned n){
if (0 == n)
return 0;
int offset = 24;
while ((n >> offset) == 0)
offset -= 8;
return highflagtable[n >> offset] + offset;
}
int中位相关的操作:最高位1的位置、最低位1的位置、1的位数、最高位连续1的位数
最新推荐文章于 2022-02-13 18:21:17 发布