前导零、后导零、最高有效位、最低有效位计算(C)

前导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;
}
相关推荐
another heaven13 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
Code_Solitude13 小时前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
Zwawa17 小时前
让屏幕动起来:OLED动画效果,丝滑光标、帧动画和一只贪吃蛇
c语言·单片机·嵌入式
꧁细听勿语情꧂18 小时前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
§ꦿCFོ༉1 天前
嵌入式八股文—C语言入门学习(四)
c语言·开发语言·学习
Severus_black2 天前
【C++初阶】Stack、Queue算法题大练兵!
c语言·c++·算法·stl
唐青枫2 天前
C 语言 strcpy() 用法详解与实战 Demo
c语言
程序猿打工仔2 天前
计算机基础(C语言)考编、专技岗
c语言·开发语言·算法
꧁细听勿语情꧂2 天前
二叉树余题,排序、直接插入排序、希尔排序
c语言·开发语言·数据结构·算法
是main不是漫2 天前
【C++——类和对象(上)】筑基篇:以封装奠定面向对象之基
c语言·开发语言·c++