如何打印字符串的位表示

std::string = "\x80";

void print (std::string &s) {

    //How to implement this
}
有帮助吗?

解决方案

我投票bitset

void pbits(std::string const& s) { 
    for(std::size_t i=0; i<s.size(); i++) 
        std::cout << std::bitset<CHAR_BIT>(s[i]) << " "; 
} 

int main() {
    pbits("\x80\x70"); 
}

其他提示

小端或大端?

for (int i = 0; i < s.length(); i++)
    for (char c = 1; c; c <<= 1) // little bits first
        std::cout << (s[i] & c ? "1" : "0");
for (int i = 0; i < s.length(); i++)
    for (unsigned char c = 0x80; c; c >>= 1) // big bits first
        std::cout << (s[i] & c ? "1" : "0");

由于我听到一些抱怨假设一个char是在其他的答案的评论的8位字节的可移植性...

for (int i = 0; i < s.length(); i++)
    for (unsigned char c = ~((unsigned char)~0 >> 1); c; c >>= 1)
        std::cout << (s[i] & c ? "1" : "0");

这是从一个非常C十岁上下的角度写的...如果你已经在使用C ++ STL的,你不如去的整套方法和利用的STL bitset的功能,而不是用绳子打。

尝试:

#include <iostream>

using namespace std;

void print(string &s) {
  string::iterator it; 
  int b;

  for (it = s.begin(); it != s.end(); it++) {
    for (b = 128; b; b >>= 1) {
      cout << (*it & b ? 1 : 0); 
    }   
  }
}

int main() {
  string s = "\x80\x02";
  print(s);
}

扩大对Stephan202的回答是:

#include <algorithm>
#include <iostream>
#include <climits>

struct print_bits {
    void operator()(char ch) {
        for (unsigned b = 1 << (CHAR_BIT - 1); b != 0; b >>= 1) {
            std::cout << (ch & b ? 1 : 0); 
        }
    }
};

void print(const std::string &s) {
    std::for_each(s.begin(), s.end(), print_bits());
}

int main() {
    print("\x80\x02");
}

最简单的解决方案是下一个:

const std::string source("test");
std::copy( 
    source.begin(), 
    source.end(), 
    std::ostream_iterator< 
        std::bitset< sizeof( char ) * 8 > >( std::cout, ", " ) );
  • 一些 stl 实现允许 std::setbase() 操纵器用于基数 2。
  • 如果想要比现有解决方案更灵活的解决方案,您可以编写自己的操纵器。

编辑:
哎呀。有人已经发布了类似的解决方案。

对不起,我此标记为重复。无论如何,要做到这一点:

void printbits(std::string const& s) {
   for_each(s.begin(), s.end(), print_byte());
}

struct print_byte {
     void operator()(char b) {
        unsigned char c = 0, byte = (unsigned char)b;
        for (; byte; byte >>= 1, c <<= 1) c |= (byte & 1);
        for (; c; c >>= 1) cout << (int)(c&1);
    }
};

如果你想要做手工,你总是可以使用一个查找表。在静态表256倍的值很难说是很大的开销:

static char* bitValues[] = 
{
"00000000",
"00000001",
"00000010",
"00000011",
"00000100",
....
"11111111"
};

然后印刷是一个简单的事情:

for (string::const_iterator i = s.begin(); i != s.end(); ++i)
{
    cout << bitValues[*i];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top