C++ - Convert unsigned character to binary string ================================================= Public domain ******************************************************************************** // g++ base.cpp -o base #include #include #include 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_