c++ - 整数到由位组成的 bool 数组,C++中最有效的方法?

标签 c++ c binary

我有一个有趣的小问题,我知道有多种方法可以给猫剥皮,但我想知道最好/最有效的方法是什么。

例如,我有一个值为 534 的整数和一个可以存储 16 个 bool 值的数组

现在,534转二进制就是10000010110

如何从 534 到

array[0] = 0
array[1] = 1
array[2] = 1
array[3] = 0
array[4] = 1
....
array[15] = 0

提前致谢!

最佳答案

使用 std::bitset<16>并调用operator[]访问各个位:

#include <iostream>
#include <bitset>

int main()
{
     std::bitset<16> bits(534);
     std::cout << bits << std::endl;

     //use operator[] to access individual bits
     std::cout << bits[2] << std::endl; 
}

输出(demo):

0000001000010110
1

这可能不是有效的,但如果您考虑安全,那么它是原始数组类型的更好替代方案。效率差异几乎可以忽略不计。

如果位数在编译时未知,而在运行时可知,则boost::dynamic_bitset会帮助你。看看它:

来自其doc ,

The dynamic_bitset class represents a set of bits. It provides accesses to the value of individual bits via an operator[] and provides all of the bitwise operators that one can apply to builtin integers, such as operator& and operator<<. The number of bits in the set is specified at runtime via a parameter to the constructor of the dynamic_bitset.

The dynamic_bitset class is nearly identical to the std::bitset class. The difference is that the size of the dynamic_bitset (the number of bits) is specified at run-time during the construction of a dynamic_bitset object, whereas the size of a std::bitset is specified at compile-time through an integer template parameter.

关于c++ - 整数到由位组成的 bool 数组,C++中最有效的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8458351/

相关文章:

c++ - NULL 指针参数有多昂贵?

c - 如何按接口(interface)过滤多播接收套接字?

c - (char) 在 ((unsigned char) ~0 >> 1) 之前的作用是什么?

c++ - 虚幻引擎 4 (ue4) 中带有自定义 c++ 蓝图函数库的蓝图循环/for/while 节点

c++ - 默认情况下,静态变量是否在 C++17 的模板中内联?

c - 在编译的二进制文件中包含一个非文本文件

java - Codility二进制周期

c++ - C++ 中的二维数组

c++ - C++ std::map 的 C 版本

mysql - MariaDB 将二进制转换为 int