前导零、后导零、最高有效位、最低有效位计算(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;
}
相关推荐
鸥梨菌Honevid1 小时前
C 语言 restrict 关键字深度解析:从“独占访问”承诺到编译器激进优化
c语言
水饺编程6 小时前
第2章:Linux 基础,切换用户
linux·c语言·汇编
知识分享小能手7 小时前
C学习教程,从入门到精通,C语言学生信息管理系统 — 知识点详解(18)
c语言·学习·1024程序员节
爱读书的小胖7 小时前
LeetCode 55 跳跃游戏 C 语言解题分析
c语言·数据结构·算法·leetcode·1024程序员节
pipixia200338 小时前
C++ 面试高频:namespace 的 6 个知识点,从 using 到匿名命名空间
c语言·学习·算法·嵌入式·命名空间·c++面试·匿名命名空间
Navigator_Z9 小时前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode
爱读书的小胖12 小时前
LeetCode 274 H 指数 C 语言解题分析
c语言·算法·leetcode·1024程序员节
Pointer Pursuit12 小时前
Linux环境变量
linux·服务器·c语言·链表·1024程序员节
CHHH_HHH13 小时前
【Linux网络篇】初识网络与Socket编程基础
linux·服务器·c语言·开发语言·网络·后端·1024程序员节