Software & Finance





Visual C++ - Decimal to Binary Conversion





Lets try writing a C program to convert a decimal number to integer with out using any string functions. The key here is the number you are going to convert will be in decimal number only even it is a binary number representing 0s and 1s.

If we have to Convert Decimal Number 5 to a binary number, then output will be 101 in decimal form only.

If we have to Convert Decimal Number 10 to a binary number, then output will be 1010 in decimal form only.

It is not that difficult since the coding for the core logic will be just 6 lines. Refer to the function int ConvertDecimal2Binary(int dec).

The complete program and test run output are given below:


Source Code


#include <iostream>

#include <string>

 

 

int ConvertDecimal2Binary(int dec)

{

    int bin = 0, pos = 1;

    while(dec > 0)

    {

        bin = bin + (dec % 2) * pos;

        dec = dec / 2;

        pos *= 10;

    }

    return bin;

}

 

int main()

{

    for(int i = 0; i < 128; i++)

    {

        if(i > 16)

            i += 7;

        char buf[128];

        sprintf(buf, "\n%3d = %08d", i, ConvertDecimal2Binary(i));

        std::cout  << buf;

    }

    std::cout << "\n\n";

    return 0;

}

 

Output


   0 = 00000000

   1 = 00000001

   2 = 00000010

   3 = 00000011

   4 = 00000100

   5 = 00000101

   6 = 00000110

   7 = 00000111

   8 = 00001000

   9 = 00001001

 10 = 00001010

 11 = 00001011

 12 = 00001100

 13 = 00001101

 14 = 00001110

 15 = 00001111

 16 = 00010000

 24 = 00011000

 32 = 00100000

 40 = 00101000

 48 = 00110000

 56 = 00111000

 64 = 01000000

 72 = 01001000

 80 = 01010000

 88 = 01011000

 96 = 01100000

104 = 01101000

112 = 01110000

120 = 01111000

128 = 10000000