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. cout << "Enter a decimal number (max 524288): ";
  13. cin >> x;
  14. cout << endl;
  15. cout << "The number in binary is: "
  16. << convertDecimalToBinary(x)<< endl; // call function...
  17. return 0;
  18. }
  19.  
  20. string convertDecimalToBinary(int value)
  21. {
  22.  
  23. const int AMOUNT = 20;
  24. int one[AMOUNT];
  25. int two[AMOUNT];
  26. // find binary and put it into an array...
  27. for(int i = AMOUNT - 1; i >= 0; i--)
  28. {
  29. one[i] = value % 2;
  30. value = value / 2;
  31. }
  32.  
  33. string s1; // create and populate string from array...
  34. for (int i = 0; i < AMOUNT; i++)
  35. {
  36. if (one[i] == 1)
  37. {
  38. s1.append("1");
  39. }
  40. else if (one[i] == 0)
  41. {
  42. s1.append("0");
  43. }
  44. }
  45.  
  46. return s1;
  47. }