Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

17
Dec

Binary to decimal

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: 21%

11
Dec

Convert integer to binary string

This function takes an unsigned long integer and places the binary string representation of the integer into a string.

void int2bin (unsigned long val, char *string)
{
  int i, j;
  unsigned long tmpval;
  char *stringPtr = &string[0];
  int cnt;
  unsigned long tval = val;
 
  //count binary digits in the integer
  for (cnt=0; tval>0; tval=tval/2,cnt++);
 
 
  for (j=0, i = cnt-1; val>0; i-- ,j++)
  {
    tmpval = val%2;
    val = val/2;
 
    if (tmpval)
    {
      *(stringPtr + i) = '0' + 1;
    }
    else
    {
      *(stringPtr + i) = '0' + 0;
    }
  }
  *(stringPtr + cnt) = '\0';
  return;
}
 
#ifdef TEST
int main()
{
  int str[10];
  int2bin(16, str);
  printf("%s\n", str);
}
#endif

download the above c program [interger_to_binary.c]

Popularity: 32%