calculate number of bits set in byte(计算以字节为单位设置的位数)
问题描述
我很感兴趣,这是通过这种方式计算字节中设置的位数的最佳方式
I am interested, which is the optimal way of calculating the number of bits set in byte by this way
template< unsigned char byte > class BITS_SET
{
public:
enum {
B0 = (byte & 0x01) ? 1:0,
B1 = (byte & 0x02) ? 1:0,
B2 = (byte & 0x04) ? 1:0,
B3 = (byte & 0x08) ? 1:0,
B4 = (byte & 0x10) ? 1:0,
B5 = (byte & 0x20) ? 1:0,
B6 = (byte & 0x40) ? 1:0,
B7 = (byte & 0x80) ? 1:0
};
public:
enum{RESULT = B0+B1+B2+B3+B4+B5+B6+B7};
};
也许在运行时知道字节值是最佳的?是否建议在代码中使用它?
Maybe it is optimal when value of byte is known at run-time? Is it recommended use this in code?
推荐答案
对于 8 位值,只需使用 256 个元素的查找表.
For 8-bit values, just use a 256-element lookup table.
对于较大尺寸的输入,它稍微不那么琐碎.Sean Eron Anderson 在他的 Bit Twiddling Hacks 页面上为此提供了几个不同的功能,所有这些功能都具有不同的性能特征.没有一个是最快的版本,因为它取决于您的处理器的性质(流水线深度、分支预测器、缓存大小等)和您使用的数据.
For larger sized inputs, it's slightly less trivial. Sean Eron Anderson has several different functions for this on his Bit Twiddling Hacks page, all with different performance characteristics. There is not one be-all-end-all-fastest version, since it depends on the nature of your processor (pipeline depth, branch predictor, cache size, etc.) and the data you're using.
这篇关于计算以字节为单位设置的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:计算以字节为单位设置的位数
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
