Search This Blog

Thursday, December 8, 2011

Printing different representations of a Number

Today I wanted to print Binary representations of 0 to 40... But I did not know how to do it.
I did knew few algorithms for conversion but I was looking for ready-made solution.

"itoa() is the required function"

Here is a simple C++ program in QT to print Decimal, Binary, Octal and Hex Representation of numbers 0 to 99



#include <QtCore/QCoreApplication>
#include <stdlib.h>
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char *argv[])
{

    QCoreApplication a(argc, argv);

    char binary_repr[12];
    char octal_repr[12];
    char hex_repr[10];

    cout << "| Decimal |  Binary  | Octal  | Hex |" << endl;
    for(int i = 0; i <=99; ++i)
    {

        _itoa_s(i, binary_repr, 2);
        _itoa_s(i, octal_repr, 8);
        _itoa_s(i, hex_repr, 16);

        cout << "|" << setw(9) <<  i
             << "|" << setw(10) << binary_repr
             << "|" << setw(8) << octal_repr
             << "|"  << setw(5) << hex_repr
             << "|" << endl;
    }
    return a.exec();
}