pointers - Decimal to Binary in C -


i'm creating program adds , subtracts 2 numbers. have output answer different bases.

my answer in decimal format, of type long double, such as:

long double answer; answer = numberone + numbertwo; 

i want convert answer binary. have code used earlier in program this, char pointer:

char * decimalbinary (char * decimalnumber)  {      bool zerofront = true;     int i;     int z;     int j = 0;     int n = atoi(decimalnumber);     char * binarynum = malloc(32+1);     binarynum[32] = '\0';      int current_index=1;     int end_index = strlen(decimalnumber)-1;      //error check valid decimal input, needed error check beginning of code     while(current_index <= end_index)     {         if(decimalnumber[current_index] != '0' &&decimalnumber[current_index] != '1' &&decimalnumber[current_index] != '2' &&decimalnumber[current_index] != '3' &&decimalnumber[current_index] != '4' &&decimalnumber[current_index] != '5' &&dec[current_index] != '6' &&dec[current_index] != '7' &&decimalnumber[current_index] != '8' &&decimalnumber[current_index] != '9')         {             binarynum[0] = -8;             return binarynum;         }         current_index++;     }       (i = 31; >= 0; i--) {         z = n >> i;          if (z & 1)          {             binarynum[j] = '1';             j++;             zerofront = false;         }         else if (!zerofront)         {             binarynum[j] = '0';             j++;         }     }      binarynum[j] = '\0';      return binarynum; } 

my preferred solution use code have in program convert answer binary format, can see parameters conflicting, , i'm not sure how go doing that.

another possible solution detracts having reusable code in program, create different function converts decimal binary, accepting parameter of type long double, bit unclear me well.

edit: instead of long double, answer of type int.

if want reuse function without modifications, can transform answer decimal string , pass string function.

char stringanswer[20]; sprintf(stringanswer, "%d", answer); printf("the binary answer %s\n", decimalbinary(stringanswer)); 

but better solution should split function decimalbinary 2 functions : first 1 check digits ok, , second 1 convert int binary string. you'll able call directly second function answer parameter.


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -