简体   繁体   English

整数到布尔数组由位组成,是c ++中最有效的方法吗?

[英]integer to boolean array made of bits, most efficient way in c++?

I have an interesting little problem, and I know there are multiple ways to skin the cat but I was wondering what would the best/most efficient way be. 我有一个有趣的小问题,我知道有多种方法可以给猫皮肤,但我想知道最好/最有效的方法是什么。

Say for example I have an integer with the value 534 and an array that can store 16 booleans 比方说,我有一个值为534的整数和一个可以存储16个布尔值的数组

now, 534 to binary is 10000010110 现在,534到二进制是10000010110

how would be the best way to get from 534 to 如何成为从534到达的最佳方式

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

thanks in advance! 提前致谢!

Use std::bitset<16> and call operator[] to access individual bits: 使用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; 
}

Output ( demo ): 输出( 演示 ):

0000001000010110
1

This may not be most efficient but if you consider safety , then it is better alternative to raw array types. 这可能不是有效的,但如果您考虑安全性 ,那么它是原始数组类型的更好替代方案。 The efficiency difference will be almost negligible. 效率差异几乎可以忽略不计。

If the number of bits is not known at compile time, and can be known at runtime, then boost::dynamic_bitset will help you. 如果在编译时未知位数,并且可以在运行时知道,那么boost::dynamic_bitset将对您有所帮助。 Have a look at it: 看看它:

From its doc , 从它的文档

The dynamic_bitset class represents a set of bits. dynamic_bitset类表示一组位。 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<<. 它通过operator []提供对各个位值的访问,并提供可以应用于内置整数的所有按位运算符,例如operator&和operator <<。 The number of bits in the set is specified at runtime via a parameter to the constructor of the dynamic_bitset. 集合中的位数在运行时通过dynamic_bitset的构造函数的参数指定。

The dynamic_bitset class is nearly identical to the std::bitset class. dynamic_bitset类几乎与std :: bitset类相同。 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. 不同之处在于dynamic_bitset的大小(位数)是在构造dynamic_bitset对象期间的运行时指定的,而std :: bitset的大小是在编译时通过整数模板参数指定的。

Like this: 像这样:

for (unsigned int i = 0; i != 16; ++i)
{
  array[i] = n & 1;
  n /= 2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM