Daniel B. answered 12/11/20
Tutor
4.9
(204)
PhD in Computer Science with 42 years in Computer Research
#include <iostream>
// Invoked like this
// BinToDec.exe 1101
// Prints
// 1101 -> 13
int main(int argc, // Should be 1 -- one argument
char *argv[]) // Binary number to be converted
{
const char *binaryNumber = argv[1];
int numBinaryDigits = strlen(binaryNumber);
unsigned long long decimalNumber = 0; // The result to be computed.
unsigned long long binaryPositionValue = 1; /* Starts with least signifficant,
then 2, 4, 8, 16, ... */
const char *binaryDigit; // Iterates over binary digits
for (binaryDigit = binaryNumber + numBinaryDigits - 1; // Least signifficant pos
binaryDigit >= binaryNumber; // Till most signifficant
binaryDigit--, // Next position
binaryPositionValue *= 2 ) { // Each binary position carried twice the value
if (*binaryDigit == '1') { // A '1', but not '0',
decimalNumber += binaryPositionValue; // contributes to the decimal number
}
}
printf("%s -> %llu\n", binaryNumber, decimalNumber); // print the result
}