将位集<64>转换为每 8 位字符串

convert bitset<64> to string every 8 bit

本文关键字:转换 字符串 lt gt      更新时间:2023-10-16

我想将std::bitset<64>转换为std::string

这是我尝试过的:

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
  }
}

结果应是一个由 8 个字符组成的字符串。

编辑

下面是一个包含 16 位的示例:

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

输出应该是包含内容ABstd::string

我不确定我是否理解你的问题。由于您的问题看起来像家庭作业,因此这里有一个可能对您有所帮助的示例,而不是实际的解决方案(演示(:

#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;
}

编辑 - 一天后

可能的解决方案(演示(:

#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;
}

这是一个非常便携的解决方案:

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;
}

演示

它使用 climits.h 定义的CHAR_BIT来获取字节中的位数(char保证为 1 字节(。

要点是我们从左到右一次处理 1 个字节的位集。

两个测试:

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;

输出:

AB
A

使用 std::bitset::to_string,如下所示:

#include <iostream>       // std::cout
#include <string>         // std::string
#include <bitset>         // std::bitset
void bitsetToChar(std::bitset<64> mybits) {
    std::bitset<8> bit;
    for(int i = 0; i < 64; ++i)
    {
        bit[i % 8] = mybits[i];
        if((i - 7) % 8 == 0)
        {
            std::string mystring = bit.to_string<char,std::string::traits_type,std::string::allocator_type>();
            std::cout << "mystring: " << mystring << 'n';
        }
    }
}
int main ()
{
  std::bitset<64> mybits;
  mybits.set();
  bitsetToChar(mybits);
  return 0;
}

输出:

Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
mystring: 11111111
mystring: 11111111
mystring: 11111111
mystring: 11111111
mystring: 11111111
mystring: 11111111
mystring: 11111111
mystring: 11111111

我认为这就是你想要做的。 在访问位集时,请注意不要越界。


如果这还不够,请查看如何将二进制值字符串转换回字符?