1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. // function returns binary string... even with preceding zeros binary number is still correct.
  6.  
  7. string convertDecimalToBinary(int value);
  8.  
  9. int main()
  10. {
  11. int x = 0;
  12. string s2("NEGATIVE NUMBER EXITING");
  13.  
  14. cout << "Enter a decimal number (max 524288): ";
  15. cin >> x;
  16. cout << endl;
  17. if(convertDecimalToBinary(x) != s2)
  18. {
  19. cout << "The number in binary is: "
  20. << convertDecimalToBinary(x)<< endl; // call function...
  21. }
  22. else
  23. {
  24. cout << s2 << endl;
  25. }
  26.  
  27. system("pause");
  28.  
  29. return 0;
  30. }
  31.  
  32. string convertDecimalToBinary(int value)
  33. {
  34.  
  35. const int AMOUNT = 20;
  36.  
  37. int one[AMOUNT];
  38. int num_digits(0);
  39. int iTemp(0);
  40. string s2("NEGATIVE NUMBER EXITING");
  41.  
  42. iTemp = value;
  43.  
  44. if(iTemp < 0)
  45. {
  46. return s2;
  47. }
  48.  
  49. while(iTemp > 0)
  50. {
  51. num_digits++;
  52. iTemp /= 2;
  53. }
  54.  
  55. for(int i = num_digits; i > 0; i--)
  56. {
  57. one[i] = value % 2;
  58. value = value / 2;
  59. }
  60.  
  61. string s1;
  62.  
  63. for (int i = 0; i <= num_digits; i++)
  64. {
  65. if (one[i] == 1)
  66. {
  67. s1.append("1");
  68. }
  69. else if (one[i] == 0)
  70. {
  71. s1.append("0");
  72. }
  73. }
  74.  
  75. return s1;
  76. }