2013-07-29 18 views
-1

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

例如,字符串“Ab3”对于“A”与“01000110”连接为“b”,连接为“11001100”连接为“3”将变为“10000010”。注意所有字符都是8位,我认为这是因为字符需要全部8位才能正确保存。如果这是真的,那么这个例子的整个字符串应该是“100000100100011011001100”

我想不出如何使用bitshift运算符来做到这一点,因为您不能将每一位转换为字符,但我知道那里必须是一种方式来做到这一点。

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

感谢您的帮助!

+0

你的问题是如何将一个字节转换为二进制字符串表示 –

+1

+1对于使用STL的答案,-1用假限制 –

+0

的问题是的,但需要为此而无需使用位集合或任何STL库。 编辑:你是什么意思“假限制”?这是一个数据结构类的项目,教授明确表示除了之外,我们不能使用任何STL库。 – user0123

回答

2

使用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; 
+0

感谢您的答案,但我不允许使用bitset这个项目。 – user0123

+0

@ user0123难道你不觉得值得一提的是你不能使用标准的类库!!! – 2013-07-29 17:55:44

+0

是的,我很抱歉,我添加了该帖子。 – user0123

3
stringstream ss; 

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

cout << ss.str(); 
+0

你是怎么知道'char'是8位宽的? – 2013-07-29 17:54:46

+0

感谢您的回复,但我不会让我们为这个项目而烦恼。 – user0123

+0

@ H2CO3,因为POSIX授权它。 –

0

我想不出该怎么办这与bitshift运算符,因为你不能将每个位转换为字符,但我知道必须有一种方式去做吧。

看起来更偏向于位移,也许?这不是一个STL函数。我敢打赌,你的教授正试图让你走向低级别的操作。

0

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

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