文字列のビット表現を出力する方法
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
他の回答のコメントで、aが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
洗練された観点から書かれています...すでにSTLでC++を使用している場合は、文字列で遊ぶ代わりに、STLビットセット機能を最大限に活用することをお勧めします。
試す:
#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, ", " ) );
編集:
おっと。誰かがすでに同様の解決策を投稿しました。
申し訳ありませんが、これを重複としてマークしました。とにかく、これを行うには:
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];
}