I have Google'd and all i found was outdated, buggy or not working
source samples. Here is what i tried but i have a bit of a problem:

void toDecimal(char bin[]){
     int i, d = 0;
     int l = strlen(bin)-1;
     int x = 1;
     for(i = 0; i < l; i++){
        int a = (bin[i] - '0');
        x *= 2;
        d = d + a * x;
        //printf("%d",d); This will just print out 1222222
        //printf("%d",x); This will just print out 1 2 4 8 16 ..
     }
}

int main(){
  toDecimal("10000001");

}

Recommended Answers

All 2 Replies

It makes more sense to work from the least significant bit (assuming your string isn't reversed), in my opinion:

#include <string.h>

int to_int(const char *bin, int *result)
{
    size_t len = strlen(bin);
    int bit_value = 1;
    int temp = 0;

    if (len > 32)
        return 0;

    while (--len < (size_t)-1) {
        int digit = bin[len] - '0';

        temp += bit_value * digit;
        bit_value *= 2;
    }

    *result = temp;

    return 1;
}
#include<stdio.h>
#include<conio.h>
#include<string.h>


void dec2bin(long decimal, char *binary)
{
    int k=0, n=0;
   char neg_flag = '0';
   int remain;
   int old_decimal; // for test
   char temp[100];


   printf("-------------------------------\nCalculating Binary value for %d\n\n", decimal);

   // take care of minus input
   if(decimal < 0)
   {
    decimal = -decimal;
      neg_flag = '1';
   }

   do
   {
    old_decimal = decimal;
      remain      = decimal%2;
      // whittle down the decimal number
      decimal     = decimal/2;
      printf("%5d/2  = %5d reminder = %5d\n", old_decimal, decimal, remain);
      temp[k++] = remain+'0';
   }while(decimal > 0);

   if(neg_flag == '1')
    temp[k++] = '-';

   // reverse spelling
   while(k>=0)
   {
     binary[n++] = temp[--k];
   }
   binary[n-1] = '\0';
   printf("-------------------------------\n");
}

int bin2dec(char *bin)
{

    int len =  strlen(bin);
        int sum = 0;
   for(int i=0; i<len; i++)
   {
    int n = bin[i] - '0'; // numerical val of bin[i] 0 or 1
      // check for a valid binary digiti

      if(n<0 || n>1)
        return -1; // error, invaild binary data

      int pv=1;
      for(int j=len; j>i+1; j--) // place value reversed
          pv *=2;

      // sum it
      sum += n*pv;
//      printf("%d*%d + ", n,pv);

   }
   return sum;
}



int main()
{
    char bin[999] = "1000";
        int dec = bin2dec(bin);
        printf("Decimal: %d", dec);
        dec2bin(dec, bin);
        printf("Binary: %s", bin);
        getch();
        return 0;
}
commented: This thread's a year old, did you have something worthwhile to add, or were you just trying to show off? -1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.