# Bit Twiddling Hacks **Repository Path**: yjf0602/bit-twiddling-hacks ## Basic Information - **Project Name**: Bit Twiddling Hacks - **Description**: https://graphics.stanford.edu/~seander/bithacks.html#OperationCounting 中文翻译 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-12-14 - **Last Updated**: 2024-12-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Bit Twiddling Hacks c/c++ 位操作运算实现的一些功能,一些场景下可用加速运算。 原文:[Bit Twiddling Hacks](https://graphics.stanford.edu/~seander/bithacks.html) 优秀翻译:[位运算的奇技淫巧:Bit Twiddling Hacks](https://blog.csdn.net/holmofy/article/details/79360859) 这里,我们加上测试代码,实际测试下这些技巧带来的速度提升作用有多大。 # 不同的机器效果可能不一样,需要实际测试来判断是否有效 # 整形符号计算 ```c int v; // 需要确定正负符号的整数; int sign; // 识别的正负符号; #define CHAR_BIT 8 // char 的位长度 // 方式 1 sign = -(v < 0); // 方式 2: 避免了有标志寄存器的 CPU 上的分支指令 sign = -(int)((unsigned int)((int)v) >> (sizeof(int) * CHAR_BIT - 1)); // 方式 3: 指令最少,速度最快,但是有些架构不支持(大部分现代处理器上都是支持的); sign = v >> (sizeof(int) * CHAR_BIT - 1); ``` 测试:TODO