Printing the Decimal Equivalent of a Binary Number. - C++ Data Type

C++ examples for Data Type:Binary

Description

Printing the Decimal Equivalent of a Binary Number.

Demo Code

#include <iostream>

int binaryToDecimal(int);

int main(int argc, const char *argv[]) {
    int binNum = 0;

    std::cout << "Enter a binary number for decimal conversion: ";
    std::cin >> binNum;//from  www  .jav  a 2  s  .  c om

    printf("%d as decimal = %d\n", binNum, binaryToDecimal(binNum));

    return 0;
}
// returns the decimal equivalent of a binary number
int binaryToDecimal(int bin) {
    int decimal = 0;
    int value = 1;

    while (bin != 0) {
        decimal += (bin % 10) * value;

        bin /= 10;
        value += value;
    }

    return decimal;
}

Result


Related Tutorials