Problem: Write a C program to convert a binary number into corresponding decimal representation using the command line argument.

Input:  11
Output: 3

Input:  10
Output: 2

Arguments from the command line can be passed to the main function as parameters. Thus the main function has to accept them in its function declarations as follows:

int main(int argc, char **argv){
    //statements
    return 0;
}

//OR

int main(int argc, char *argv[]){
    //statements
    return 0;
}
  • argc – The number of arguments passed.
  • argv – The values of arguments passed (values are passed as an array of strings).

The argv parameter stores the name of the file in the first index (i.e. argv[0]) and afterwards the arguments.

The interpreter always passes the file name as the first argument. Therefore the default value of argc is 1.

Let’s see how can we convert the passes binary into decimal.

Method 1: As Binary String

#include <stdio.h> 
#include <math.h>

int main(int argc, char **argv) {
    //store number as character
    char *N = argv[1]; 
    
    int digits, decimal = 0; 
    
    //counting digits
    for(digits=0; N[digits] != '\0'; digits++); 
    
    //loop through each digits of the number
    for(int i=0; i<digits; i++){
        //multiply with 2^x and add to decimal
        decimal += ((pow(2,digits-1-i)) * ((int) N[i] -48)); 
    }
    
    //output the decimal
    printf("%d", decimal);
    return 0; 
}

Command Line:

$./a.out 11

Output: 3

Explanation:

  1. Read the passed binary value and store it in the char array.
  2. Count the number of digits in the binary.
  3. Loop through each digit of the binary.
    1. Convert the digit of char into of type int (typecasting the character to integer, which will give its ASCII value. and subtract 48).
    2. Add the digit to decimal after multiplying the value of 2n-1.

Method 2: As Binary Number

#include <stdio.h> 
#include <math.h>

int main(int argc, char **argv)
{
    //store the binary number
    int N = atoi(argv[1]);
    int digits = 0, decimal = 0;

    int num = N;
    
    //count digits in binary
    while(num>0){
        digits++;
        num=num/10;
    }

    num = N;
    
    //loop through the binary digits
    for(int i=0; i<digits; i++){
        //multiply by 2x and add to decimal
        decimal += ((pow(2,i)) * (num%10));
        num= num/10;
    }
        
    //output the decimal
    printf("%d", decimal);
    return 0;
    
}

atoi(char *str) is a function from c standard library that converts string into integer.

Command Line:

$./a.out 11

Output: 3

Note: For the above program to work, you have to correctly pass a binary value as a command-line argument.

Leave a Reply