View Single Post
 
binary to decimal
Reply
Posted 2004-12-04, 12:43 PM
I need some help I need to write a program that a user inputs a string of 32 0's and 1's representing a binary number. then I need to convert the binary integer to its base 10 representation and then back.


Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


long     BinaryToDecimal(const char * pstrBinary)
{
     int     intLoop=0;
     long     lngReturn=0L;
     long     lngMultip=1L;
     for (intLoop=0; intLoop < (int)strlen(pstrBinary); intLoop++)
          {
          if ('1' == pstrBinary[intLoop])
            {
             lngReturn += lngMultip;
            }
          lngMultip *= 2;
          }
     return lngReturn;
}


char     *     DecimalToBinary(long lngDecimal)
{
     static     char strReturn[128]={0};
     _ltoa(lngDecimal, strReturn, 2);
     return strReturn;
}


int main(void)
{
     long          lngDecimal     =     7;
     char     *     pstrBinary     =     "111";
     printf("B2D=%ld\nD2B=%s\n", BinaryToDecimal(pstrBinary),DecimalToBinary(lngDecimal));
}

Last edited by deadlock75; 2004-12-04 at 01:09 PM.
Old
Profile PM WWW Search
deadlock75 is neither ape nor machine; has so far settled for the in-betweendeadlock75 is neither ape nor machine; has so far settled for the in-between
 
deadlock75