Follow us on Twitter!
The important thing is not to stop questioning. - Albert Einstein
Thursday, April 24, 2014
Navigation
Home
HellBoundHackers Main:
HellBoundHackers Find:
HellBoundHackers Information:
Learn
Communicate
Submit
Shop
Challenges
HellBoundHackers Exploit:
HellBoundHackers Programming:
HellBoundHackers Think:
HellBoundHackers Track:
HellBoundHackers Patch:
HellBoundHackers Other:
HellBoundHackers Need Help?
Other
Members Online
Total Online: 23
Guests Online: 18
Members Online: 5

Registered Members: 82895
Newest Member: kevy90
Latest Articles
View Thread

HellBound Hackers | Computer General | Programming

Author

Help converting Binary to Decimal in C


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 16-09-08 01:04
Hey all,

I am struggling with figuring out the source code on how to convert binary to decimal.

I know that you need to take each digit in the binary number and raise it to the base and power of however many digits there are, like so...

1011 = 1x 2^3 + 0x 2^2 + 1x 2^1 + 1x 2^0 ... which would give the decimal number of 1011.

Could someone please help me figure out how to get this to work in C?


Author

RE: Help converting Binary to Decimal in C


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 16-09-08 01:19
Code

#include <stdio.h>
 
void dec2bin(long decimal, char *binary);
 
int main()
{
  long decimal;
  char binary[80];
 
  printf("\n\n Enter an integer value : ");
  scanf("%ld",&decimal);
  dec2bin(decimal,binary);
  printf("\n The binary value of %ld is %s \n",decimal,binary);
 
  getchar();  // trap enter
  getchar();  // wait
  return 0;
}
 
//
// accepts a decimal integer and returns a binary coded string
//
void dec2bin(long decimal, char *binary)
{
  int  k = 0, n = 0;
  int  neg_flag = 0;
  int  remain;
  int  old_decimal;  // for test
  char temp[80];
 
  // take care of negative input
  if (decimal < 0)
  {     
    decimal = -decimal;
    neg_flag = 1;
  }
  do
  {
    old_decimal = decimal;   // for test
    remain    = decimal % 2;
    // whittle down the decimal number
    decimal   = decimal / 2;
    // this is a test to show the action
    printf("%d/2 = %d  remainder = %d\n", old_decimal, decimal, remain);
    // converts digit 0 or 1 to character '0' or '1'
    temp[k++] = remain + '0';
  } while (decimal > 0);
 
  if (neg_flag)
    temp[k++] = '-';       // add - sign
  else
    temp[k++] = ' ';       // space
 
  // reverse the spelling
  while (k >= 0)
    binary[n++] = temp[--k];
 
  binary[n-1] = 0;         // end with NULL
}





Blah attempt 2 at answering your question... Anyways here's one I quickly found on google.




Edited by on 16-09-08 01:25
Author

RE: Help converting Binary to Decimal in C

ynori7
Member



Posts: 1486
Location: #valhalla
Joined: 08.10.07
Rank:
God
Posted on 16-09-08 01:40
Here ya go, read through this:

Code
/************************************
 * convert.c -- Converts a number from
 *      one base to another, up to 5 places
 *      after the point precision.
 *    Without using stdlib functions in added code.
 *
 * by ynori7
 * Feb 5, 2008
 ************************************/

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

/*****************************************************
 * Converts a character to its corresponding int:
 * chToInt('0') => 0, chToInt('a') => 11, chToInt('B') => 12, etc.
 ******************************************************/
int chToInt(char c) {
    char ls[]="0123456789abcdefghijklmnopqrstuvwxyz";
   char ls2[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   for (int x=0; x<strlen(ls); x++)
   {
      if(c==ls[x])
      {return x;}
   }
   for (int x=0; x<strlen(ls2); x++)
   {
      if(c==ls2[x])
      {return x;}
   }
   return 0;
}

/*************************************************
 * Converts an int to its corresponding char:
 * intToCh(1) => '1', intToCh(11) => 'a', intToCh(15) => 'f'
 *******************************************************/
char intToCh(int i) {
   char ls[]="0123456789abcdefghijklmnopqrstuvwxyz";
   return ls[i];
}

/*****************************
 * returns the position of the first occurence of mNeedle in mHaystack
 * -1 if not found
 *****************************/
int strpos(char mNeedle, char* mHaystack) {
   int i;
   for(i = 0; i < strlen(mHaystack); i++) if(mHaystack[i] == mNeedle) return i;
   return -1;
}

/***********************************************
 * convert: converts the string mInput from base
 *      mBase1 to mBase2, and returns a string representation
 ***********************************************/
char* convert(char* mInput, int mBase1, int mBase2) {
  char whole[99];
  char whole2[99];
  char fraction[99];
  char* output=malloc(sizeof(char)*100);
  int bTen=chToInt(mInput[0]);
  double bTenDec=0;
  int point=0;
  int x=0, y=0, w=0, p=0, exp=0;

  for(x=1; x<strlen(mInput); x++)//convert the whole part of the number into base 10
  {
     if(mInput[x]=='.'){point=1; break;}
     bTen*=mBase1;
     bTen+=chToInt(mInput[x]);
  }

  if(point==1)//convert the fraction part of the number into base 10
  {
     exp=1;
     for(y=x+1; y<strlen(mInput); y++)
       {
        bTenDec+=chToInt(mInput[y])* pow(mBase1, -exp);
        exp++;
      }
  }
///////////////////////////////////////////////////////////////
     x=0;
     while( bTen > 0 )//convert the whole part of the base 10 number to the new base
      {
            whole[x] = intToCh(bTen%mBase2);
            bTen = (bTen-bTen%mBase2)/mBase2;
         x++;
      }
     x--;
     w=0;
     for(x=x; x>=0; x--)//reverse it becuase it got stored in reverse order in the conversion
     {
        output[w]=whole[x];
        w++;
     }
///////////////////////////////////////////////////////////////
     y=0;
     while(1)//convert the fraction part of the base 10 number to the new base
      {
          bTenDec*=mBase2;
         if(floor(bTenDec)<bTenDec)
          {
            fraction[y]=intToCh(floor(bTenDec));
            bTenDec-=floor(bTenDec);
         }
         else if(floor(bTenDec)==bTenDec)
          {
            fraction[y]=intToCh((int)bTenDec);
            break;
          }
         y++;
      }
     if(y<5)
     {
        y++;
        for(y=y; y<5; y++)
        {
           fraction[y]='0';
        }
     }
  x=0;
  output[w]='.';
  w++;
  for(p=w; p<(w+y+1); p++)//put the whole and fraction parts together.
  {
     output[p]=fraction[x];
     x++;
  }
  output[p]='\0';

   return output;
}

/**************************
 * main function
 ***************************/
int main(int argc, char** argv) {
  if(argc < 4) {
    fprintf(stderr,"Error, not enough arguments.\n");
    fprintf(stderr,"Usage: convert number base1 base2\n");
    exit(1);
  }
   char* num = argv[1];
   char* num2;
   int tFrom = atoi(argv[2]);
   int tTo = atoi(argv[3]);

   num2 = convert(num, tFrom, tTo);

   printf("%s (base %d) = %s (base %d)\n",num, tFrom, num2, tTo);

  return 0;
}



That converts from any base (2-36 or something like that, dont remember) to any other base.


halls-of-valhalla.org/images/affiliateLogo.png voodoorage.halls-of-valhalla.org/images/smallLogo.png
i537.photobucket.com/albums/ff338/ynori77/archenemysig1.jpg


Edited by ynori7 on 16-09-08 01:41
ynori7 http://halls-of-valhalla.org
Author

RE: Help converting Binary to Decimal in C


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 16-09-08 01:50
Very nice code, I enjoy walkin through it. gj Wink


Author

RE: Help converting Binary to Decimal in C


Member

Your avatar

Posts:
Location:
Joined: 01.01.70
Rank:
Guest
Posted on 16-09-08 02:50
It's been a while since I've written any C, so I'll just do it in pseudocode:

Put the integer in an array
result = 0
count = total number of elements in the array
for x = count - 1 to 0 {
result += array[x]^(2 * (count - x - 1)
}

Yeah, hate me... I'll redo it in C after I get my X resolutions fixed.