Software & Finance





Visual C++ - Binary to Decimal Conversion





Lets try writing a C program to convert a binary number to decimal number 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 Binary Number 101 to a decimal number(5), then input will be 101 in decimal form only.

If we have to Convert Binary Number 1010 to a decimal number(10), then input 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 ConvertBinary2Decimal(int bin).

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 ConvertBinary2Decimal(int bin)

{

    int dec = 0, pos = 0;

    int factor = 1;

 

    while(bin > 0)

    {

        if( (bin % 10) == 1)

        {

            dec += factor;

        }

        bin /= 10;

        pos++;

        factor = factor * 2;

    }

 

    return dec;

}

 

int main()

{

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

    {

        if(i > 16)

            i += 7;

        char buf[128];

        int bin = ConvertDecimal2Binary(i);

        int dec = ConvertBinary2Decimal(bin);

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

        std::cout  << buf;

    }

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

    return 0;

}

Output


  0 = 00000000 =   0

  1 = 00000001 =   1

  2 = 00000010 =   2

  3 = 00000011 =   3

  4 = 00000100 =   4

  5 = 00000101 =   5

  6 = 00000110 =   6

  7 = 00000111 =   7

  8 = 00001000 =   8

  9 = 00001001 =   9

 10 = 00001010 =  10

 11 = 00001011 =  11

 12 = 00001100 =  12

 13 = 00001101 =  13

 14 = 00001110 =  14

 15 = 00001111 =  15

 16 = 00010000 =  16

 24 = 00011000 =  24

 32 = 00100000 =  32

 40 = 00101000 =  40

 48 = 00110000 =  48

 56 = 00111000 =  56

 64 = 01000000 =  64

 72 = 01001000 =  72

 80 = 01010000 =  80

 88 = 01011000 =  88

 96 = 01100000 =  96

104 = 01101000 = 104

112 = 01110000 = 112

120 = 01111000 = 120

128 = 10000000 = 128

 

Press any key to continue . . .