decimal integer do a binary string

  1. // Convert a decimal integer do a binary string
  2. // added a test printf() you can remove later
  3. // Turbo C modified for Pelles C vegaseat 19nov2004
  4. /*
    author              :sailesh Kumar
    Website             :www.yongsters.co.cc
    Organisation        :saileshkumar.org
    
    */
  5. #include <stdio.h>
  6. void dec2bin(long decimal, char *binary);
  7. int main()
  8. {
  9. long decimal;
  10. char binary[80];
  11. printf("\n\n Enter an integer value : ");
  12. scanf("%ld",&decimal);
  13. dec2bin(decimal,binary);
  14. printf("\n The binary value of %ld is %s \n",decimal,binary);
  15. getchar(); // trap enter
  16. getchar(); // wait
  17. return 0;
  18. }
  19. //
  20. // accepts a decimal integer and returns a binary coded string
  21. //
  22. void dec2bin(long decimal, char *binary)
  23. {
  24. int k = 0, n = 0;
  25. int neg_flag = 0;
  26. int remain;
  27. int old_decimal; // for test
  28. char temp[80];
  29. // take care of negative input
  30. if (decimal < 0)
  31. {
  32. decimal = -decimal;
  33. neg_flag = 1;
  34. }
  35. do
  36. {
  37. old_decimal = decimal; // for test
  38. remain = decimal % 2;
  39. // whittle down the decimal number
  40. decimal = decimal / 2;
  41. // this is a test to show the action
  42. printf("%d/2 = %d remainder = %d\n", old_decimal, decimal, remain);
  43. // converts digit 0 or 1 to character '0' or '1'
  44. temp[k++] = remain + '0';
  45. } while (decimal > 0);
  46. if (neg_flag)
  47. temp[k++] = '-'; // add - sign
  48. else
  49. temp[k++] = ' '; // space
  50. // reverse the spelling
  51. while (k >= 0)
  52. binary[n++] = temp[--k];
  53. binary[n-1] = 0; // end with NULL
  54. }