如何打印字符串的位表示
std::string = "\x80";
void print (std::string &s) {
//How to implement this
}
答案 0 :(得分:6)
我投票给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");
}
答案 1 :(得分:4)
Little-endian还是big-endian?
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
- ish的观点写的...如果你已经在使用带有STL的C ++,你可能会全力以赴并利用STL bitset功能而不是玩字符串。
答案 2 :(得分:3)
尝试:
#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);
}
答案 3 :(得分:3)
扩展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");
}
答案 4 :(得分:3)
接下来是最简单的解决方案:
const std::string source("test");
std::copy(
source.begin(),
source.end(),
std::ostream_iterator<
std::bitset< sizeof( char ) * 8 > >( std::cout, ", " ) );
修改强>
哎呀。有人已经发布了类似的解决方案。
答案 5 :(得分:1)
对不起,我将此标记为副本。无论如何,要做到这一点:
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);
}
};
答案 6 :(得分:0)
如果您想手动执行此操作,则始终可以使用查找表。静态表中的256个值几乎不需要很多开销:
static char* bitValues[] =
{
"00000000",
"00000001",
"00000010",
"00000011",
"00000100",
....
"11111111"
};
然后打印就是一个简单的问题:
for (string::const_iterator i = s.begin(); i != s.end(); ++i)
{
cout << bitValues[*i];
}