将字符串转换为表示这些字符的1和0字符串

Converting a string of characters to a string of 1s and 0s that represent those characters

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

我想将一个字符串(显然每个字节)转换为一个1和0的字符串,这些字符串表示每个字符的二进制代码,首先是最低有效位。

例如,字符串"Ab3"将变为"10000010"表示"A","01000110"表示"b","11001100"表示"3"。注意所有的字符都是8位,我认为是这样的,因为字符需要有所有的8位才能正确保存。如果这是真的,那么这个例子的整个字符串应该是"10000000100011011001100"

我想不出如何用比特移位运算符来实现这一点,因为你不能把每个比特都转换成一个字符,但我知道一定有办法做到这一点。

注意:我不允许在此项目中使用位集(或任何STL)。

谢谢你的帮助!

stringstream ss; 
for(char c: std::string("Ab3")) 
     ss << std::bitset<8>(c);  
cout << ss.str();

使用std::bitset:

#include <iostream>
#include <bitset>
#include <climits>
int main()
{
    std::string bits;
    std::string s = "abcd";
    for (std::string::iterator it = s.begin(); it != s.end(); it++) {
        std::bitset<CHAR_BIT> bset;
            bset |= (unsigned char)*it;
            bits += bset.to_string();
    }
    std::cout << bits << std::endl;
    return 0;
}

编辑:根据愚蠢的限制重写相关部分:

std::string bits;
std::string s = "abcd";
for (std::string::iterator it = s.begin(); it != s.end(); it++) {
    unsigned char c = *it;
    for (int i = CHAR_BIT - 1; i >= 0; i--)
        bits += '0' + ((c >> i) & 1);
}
std::cout << bits << std::endl;

我想不出如何用比特移位运算符来实现这一点,因为你不能把每个比特都转换成一个字符,但我知道一定有办法做到这一点。

也许多看一点比特移位?这不是STL函数。我敢打赌,你的教授正试图把你推向低水平的钻头操作。

您将需要使用位移位和掩码。

void output_binary_rep(const std::string text&, std::ostream& output)
{
    // Look up CHAR_BIT, which contains the number of bits per character.
    const unsigned int length = text.length();
    // For each character in the string, do:
    for (unsigned int i = 0U; i < length; ++i)
    {
        // For each bit in the character, output a '1' or '0'.
        for (unsigned int j = 0; j < CHAR_BIT; ++j)
        {
             // Isolate a bit, from MSB to LSB, using
             // a 1 left shited by a number of bits.
             if (text[i] & (1 << (CHAR_BIT - j - 1)))
             {
                 output << "1";
             }
             else
             {
                 output << "0";
             }
        }
    }
}