Search code examples
c++stringloopsbit-manipulationbitset

convert bitset<64> to string every 8 bit


I want to convert a std::bitset<64> to a std::string.

Here's what I have tried:

std::string bitsetToChar(std::bitset<64> bitset){
  std::bitset<8> bit;

  for(int i=0;i<8;i++){
    for(int j=0;j<8;j++){
      bit[j] = bitset[i*8+j];
    }
    // new char c using above bits
    // link chars
  }
}

The result should be a string consisting of 8 chars.

Edit

Here's an example with 16 bits:

 bitset<16> bits = 0100000101000010;
 // first 8 bit is 01000001, second is 01000010

Output should be a std::string with content AB.


Solution

  • Here's a pretty portable solution:

    template<size_t N>
    std::string bitset_to_string(std::bitset<N> bits){
        static_assert(N % CHAR_BIT == 0, L"bitset size must be multiple of char");
        std::string toReturn;
        for(size_t j = 0; j < N/CHAR_BIT; ++j)
        {
            char next = 0;
            for(size_t i = 0; i < CHAR_BIT; ++i)
            {
                size_t index = N - (CHAR_BIT*j) - i - 1;
                size_t pos = CHAR_BIT - i - 1;
                if (bits[index])
                    next |= (1 << pos); 
            }
            toReturn.push_back(next);
        }
        return toReturn;
    }
    

    Demo

    It uses CHAR_BIT as defined by climits.h to get the number of bits in a byte (and a char is guaranteed to be 1 byte).

    The gist is that we process the bitset 1 byte at a time from left to right.

    Two tests:

    std::bitset<16> bits{"0100000101000010"}; // AB
    std::bitset<8> bits2{"01000001"};
    std::cout << bitset_to_string(bits) << std::endl;
    std::cout << bitset_to_string(bits2) << std::endl;
    

    Output:

    AB
    A