Pejman Moghadam / C-programming

C++ - Convert unsigned character to binary string

Public domain


// g++ base.cpp -o base
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;

char *ch2bin(unsigned char a)
{
    static char b[9];
    for (unsigned char i = 128, j = 0; i > 0; i >>= 1, j++)
        b[j] = a&i ? '1':'0';
    b[8] = '\0';
    return b;
}

int main()
{
    char binary[9];
    for (int i = 0; i < 256 ; i++) {
        strcpy(binary, ch2bin(i));
        cout << setw(3) << left;
        cout << (int)i << " = ";
        cout << binary << endl;
    }
    return 0;
}

BY: Pejman Moghadam
TAG: cpp, binary, string, base
DATE: 2012-08-08 22:09:11


Pejman Moghadam / C-programming [ TXT ]