简体   繁体   中英

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

now, 534 to binary is 10000010110

how would be the best way to get from 534 to

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:

#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. Have a look at it:

From its 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.

Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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