Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

17
Dec

Binary to decimal

Related Blog Items

Binary System:

Base: 2
Digits: 0, 1
Example: 27 (decimal) = 11011 (binary)

Decimal System:
Base: 10
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Binary 2 Decimal conversion Example

Transform 110101 (binary) into decimal number
111001 = 1*(2^5)+ 1*(2^4) + 1*(2^3) + 0*(2^2) + 0*(2^1) + 1*(2^0) = 32 + 16+ 8 +0 +0+1 = 57

int convert_bin2dec(char *binstring)
{
  int j=0,sum=0,tmp;
  int len = strlen(binstring);
 
  for(j=0;j<len;j++)
  {
    if(binstring[j]!='1' && binstring[j]!='0')
    {
      printf("not a binary no");
      return -1;
    }
  }
 
  tmp = len-1;
  for(j=0; j<len; j++)
  {
    sum=sum+((binstring[j]-'0')*(tmp?(2<<tmp-1):1));
    tmp - -;
  }
  return sum;
}
 
#ifdef TEST
int main()
{
  char str[20]="10000000000";
  printf("%d\n", convert_bin2dec(str));
}
#endif

download binary to decimal conversion program [binary_to_decimal.c]

Popularity: 20%

You need to log on to convert this article into PDF


Related Blog Items

2 Comments

  • Sridhar  said:

    Hi,
    Check the input no, 10010, it is giving as 9, where as expected is 18. I think this prog is treating given number reversely and calculating for that. Check the second-for loop and adjust for proper value printing.

    Sridhar


  • ponnada  said:

    Yes, it was wrong…
    the second loop should start from i-1 instead of zero

    so, I’ve modified that this way for(j=i-1; j


Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image