gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:40:52 35 4
gpt4 key购买 nike

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

例如,我有一个值为 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com