I don't understand why do you convert the bitset to string. Just access it's elements directly.
bitset<10> myBitset(myValue);
for (int i = 0; i < 10; i++)
binary[i] = myBitset[i];
You could also go with bit shifting, that's the most low level way of doing this:
int mask = 1; // binary 10000000 00000000 ...
for (int i = 0, l = NUM_BITS; i < l; ++i) {
// binary & operation does
// AND logic operation for all corresponging bit
// so 0010&0011=0010
binary[i] = myValue & mask;
// move the bits in mask one to the right
mask = mask>>1;
}
If you're going with bitset, I'd recommend that you keep the bitset instead of using bool* because in bitsets, every bit actually occupies one bit, whereas bool is eight bits large at least.
Finally, here's some test code I made for that, you can use it to do benchmarks:
#include <iostream>
#include <bitset>
#define NUM_BITS 10
int main(int argc, char *argv[])
{
const int numBits = NUM_BITS;
bool binary[numBits];
const int myValue = 1;
std::bitset<NUM_BITS> myBitset(myValue);
//for (int i = 0; i < NUM_BITS; i++)
//binary[i] = myBitset[i];
for (int i = 0, l = NUM_BITS; i < l; ++i) {
std::cout<< (binary[i]?'1':'0')<<" ";
}
std::cout<<"\n";
int mask = 1; // binary 10000000 00000000 ...
for (int i = 0, l = NUM_BITS; i < l; ++i) {
// binary & operation does
// AND logic operation for all corresponging bit
// so 0010&0011=0010
binary[i] = myValue & mask;
// move the bits in mask one to the right
mask = mask>>1;
}
for (int i = 0, l = NUM_BITS; i < l; ++i) {
std::cout<< (binary[i]?'1':'0')<<" ";
}
}
.to_ulongdidn't really worked well for me. That's what I want to get rid of.bitset<10>can be stored in a variable, and then use the variable in a loop?