Search code examples
c++arraysbitset

How do I convert bitset to array of bytes/uint8?


I need to extact bytes from the bitset which may (not) contain a multiple of CHAR_BIT bits. I now how many of the bits in the bitset I need to put into an array. For example,

the bits set is declared as std::bitset < 40> id;

There is a separate variable nBits how many of the bits in id are usable. Now I want to extract those bits in multiples of CHAR_BIT. I also need to take care of cases where nBits % CHAR_BIT != 0. I am okay to put this into an array of uint8


Solution

  • Unfortunately there's no good way within the language, assuming you need for than the number of bits in an unsigned long (in which case you could use to_ulong). You'll have to iterate over all the bits and generate the array of bytes yourself.