前导0(CLZ)
c
int32_t count_leading_zeros(uint32_t input) {
if (input == 0) return 32; // 全0的特例
int clz = 0;
if (!(input >> 16)) { clz += 16; x <<= 16; }
if (!(input >> 24)) { clz += 8; x <<= 8; }
if (!(input >> 28)) { clz += 4; x <<= 4; }
if (!(input >> 30)) { clz += 2; x <<= 2; }
if (!(input >> 31)) { clz += 1; }
return clz;
}
后导0(CTZ)
c
int32_t count_trailing_zeros(uint32_t input)
{
if (input == 0) return 32;
int ctz = 0;
if ((input & 0xFFFF) == 0) { ctz += 16; x >>= 16; }
if ((input & 0xFF) == 0) { ctz += 8; x >>= 8; }
if ((input & 0xF) == 0) { ctz += 4; x >>= 4; }
if ((input & 0x3) == 0) { ctz += 2; x >>= 2; }
if ((input & 0x1) == 0) { ctz += 1; }
return ctz;
}
计算最高有效位(MSB)
c
int highest_bit_position(uint32_t x) {
if (x == 0) return -1;
int position = 0;
if (x >> 16) { position += 16; x >>= 16; }
if (x >> 8) { position += 8; x >>= 8; }
if (x >> 4) { position += 4; x >>= 4; }
if (x >> 2) { position += 2; x >>= 2; }
if (x >> 1) { position += 1; }
return position;
}
计算最低有效位(LSB)
c
int find_lowest_bit_position(uint32_t x) {
if (x == 0) return -1;
int position = 0;
if ((x & 0x0000FFFF) == 0) { position += 16; x >>= 16; }
if ((x & 0x000000FF) == 0) { position += 8; x >>= 8; }
if ((x & 0x0000000F) == 0) { position += 4; x >>= 4; }
if ((x & 0x00000003) == 0) { position += 2; x >>= 2; }
if ((x & 0x00000001) == 0) { position += 1; }
return position;
}