Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

I'm not sure that I understood your problem. Since your question looks like homework, here's an example that might help you, not the actual solution (demo):

#include <iostream>
#include <bitset>

int main()
{
  std::bitset<16> b { "0100000101000010" }; // "AB"
  std::bitset<16> m { "0000000011111111" }; // 0xff
  for ( int i = 0; i < 2; ++i )
  {
    std::cout << char( ( b & m ).to_ullong() ); // will display "BA"
    b >>= 8;
  }
  return 0;
}

EDIT - one day later

A possible solution (demo):

#include <iostream>
#include <string>
#include <bitset>

template < std::size_t N >
std::string to_text( std::bitset< N > b )
{
  return b.any()
    ? to_text( b >>= 8 ) + char( b.to_ullong() & 0xff )
    : "";
}

int main()
{
  std::cout << to_text( std::bitset<16> { "0100000101000010" } );
  return 0;
}
like image 102
zdf Avatar answered Apr 09 '26 09:04

zdf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!