Hi everyone,

I'm new here but have found it super useful to search the forums when encountering problems so I have been in the background. I am however really stuck with bitsets and have not been able to find a relevant post here or on the internet.

My issues is that I have a number of bitsets that I need to concatenate preferably as char arrays as I know hoe to do this. I can't for the life of me find a way to convert a bitset to a char array. I have tried all sorts from stringstream to sprint but nothing seems to work properly and I keep getting errors.

Does anyone know of a method to convert a bitset into a char array?

Much thanks for your time reading this,

Richard

Recommended Answers

All 4 Replies

P.s i have tried to use the .to_string operator but can't get that work either!

I'm guessing the to_ulong() function is not good enough, i.e., you have too many bits in the bitset. If you can use it, then you can always memmove() the resulting unsigned long into an array: char[sizeof(unsigned long)].

If the bitset is bigger, consider splitting it up.

Otherwise, I don't know, I guess you would have use a loop, which, of course, defeats the purpose of the bitset. I don't think the C++ guys expected people to use bitset for anything larger than unsigned long. I know it is inefficient, buy one loop could be:

bitset<128> bits; //say you have 128 bits.
unsigned char binstr[16] = {0}; //that requires 16 bytes to store it in.
for(int i=0; i<16; ++i) {
  for(int j=0; j<8; ++j) {
    if(bits[j + i*8])
      binstr[i] += 1 << j;
  };
};

sorry, can't help you more than that.

Wait! are you trying to convert it to a string or a binary memory dump?

If you want a string, as a char array, like one char '0' or '1' for each bit, then use the to_string() function. Like this, for instance:

bitset<128> bits; //say you have 128 bits.
char binstr[129]; //that requires 128 chars + 1 null-char to store it in.
strcpy(binstr,bits.to_string().c_str());
commented: Sorted a problem that I had spent 6 hours on, thanks! a* +0

Hi Mike,

The bitsets were 8 bits wide so they could have gone to Long but I would have preferred Char as I know how to join char arrays. That solution you provided was spot on! I really appreciate the help, great poster.

Many thanks,

Richard

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.