How to print the bit representation of a string
std::string = "\x80";
void print (std::string &s) {
//How to implement this
}
How to print the bit representation of a string
std::string = "\x80";
void print (std::string &s) {
//How to implement this
}
Try:
#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);
}
Little-endian or 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");
Since I hear some grumbling about portability of assuming that a char
is a 8-bit byte in the comments of the other answers...
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");
This is written from a very C
-ish standpoint... if you're already using C++ with STL, you might as well go the whole way and take advantage of the STL bitset functionality instead of playing with strings.
I am sorry I marked this as a duplicate. Anyway, to do this:
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);
}
};
expanding on Stephan202's answer:
#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");
}
I'd vote for 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");
}
Easiest solution is next:
const std::string source("test");
std::copy(
source.begin(),
source.end(),
std::ostream_iterator<
std::bitset< sizeof( char ) * 8 > >( std::cout, ", " ) );
EDIT:
Oops. Someone already posted similar solution.
If you want to do it manually, you can always use a lookup table. 256 values in a static table is hardly a lot of overhead:
static char* bitValues[] =
{
"00000000",
"00000001",
"00000010",
"00000011",
"00000100",
....
"11111111"
};
Then printing is a simple matter of:
for (string::const_iterator i = s.begin(); i != s.end(); ++i)
{
cout << bitValues[*i];
}