carraysstringfunction-calls

Binary to Decimal Converter with C


I am new at writing in C, and I am not quite understanding why this programme is resulting in a failure. I feel like it is a result of the method isTrue. The purpose of the method was to ensure that the string entered was an actual integer, but it doesn't seem to work there. I am not really sure why. I get some weird values returned for some reason.

/* Program: binToDec.c
   Author: Sayan Chatterjee
   Date created:1/25/17
   Description:
     The goal of the programme is to convert each command-line string
     that represents the binary number into its decimal equivalent 
     using the binary expansion method.
*/

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

/*Methods*/
int strLen(char *str);
int isTrue(char *str);
int signedBinToDec(char *str);

/*Main Method*/
int main(int argc, char **argv)
{
  /*Declaration of Variables*/
  int binNum = 0;
  int decNum = 0;
  int i;

  /*Introduction to the Programme*/
  printf("Welcome to Binary Converter\n");
  printf("Now converting binary numbers\n");
  printf("...\n");

  /*Check to see any parameters*/
  if(argc > 1)
  {
    for(i = 1; i < argc; i++)
    {
      if(isTrue(argv[i] == 1))
      {
        if(strLen(argv[i] <= 8))
        {
          binNum = atoi(argv[i]);
          decNum = signedBinToDec(binNum);
        }
        else
        {
          printf("You did not enter a 8-bit binary\n\a");
          break;
        }
        break;
      }
      else
      {
        printf("You did not enter a proper binary number\n\a");
        break;
      }
    } 

    /*Printing of the Result*/
    printf("Conversion as follows: \n");
    printf("%d\n", decNum);

  }
  else
  {
    printf("You did not enter any parameters. \a\n");
  }
}

int strLen(char *str)
{
  int len = 0;
  while(str[len] != '\0')
  {
    len++;
  }
  return len;
}

int isTrue(char *str)
{
  int index = 0;
  if(str >= '0' && str <= '9')
  {
    return 1;
  }
  else
  {
    return 0;
  }
}


int signedBinToDec(char *str)
{
  int i;
  int len = strLen(str);
  int powOf2 = 1;
  int sum = 0;

  for(i = len-1; i >= 0; i--)
  {
    if(i == 0)
    {
      powOf2 = powOf2 * -1;
    }
    sum = (str[i]*powOf2) + sum;
    powOf2 = powOf2 * 2;
  }
  return sum;
}

Solution

  • The if statement

      if( isTrue(argv[i] == 1) )
    

    is very wrong. It is bad because of two cases

    It appears, you meant to write

      if ( isTrue(argv[i]) == 1 )
    

    as you need to compare the return value of isTrue call.

    The same goes for strLen(argv[i] <= 8) and others.


    That said, there are other problems.