Advertisement
193030

Decimal to binary

Apr 17th, 2020
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. // Example program
  2. #include <iostream>
  3. #include <string>
  4. #include <cmath>
  5. using namespace std;
  6.  
  7. unsigned GetNumberOfDigits (unsigned i)
  8. {
  9.     return i > 0 ? (int) log10 ((double) i) + 1 : 1;
  10. }
  11.  
  12. void reverseStr(string& str)
  13. {
  14.     int n = str.length();
  15.  
  16.     // Swap character starting from two
  17.     // corners
  18.     for (int i = 0; i < n / 2; i++)
  19.         swap(str[i], str[n - i - 1]);
  20. }
  21.  
  22.  
  23. string decimalToBinary(int input, int len=0)
  24. {
  25.     len=1+floor(log10(input));//c++ code lib (cmath)
  26.     int temp = input;
  27.     string output = "";
  28.     while(1)
  29.     {
  30.         if(temp==1)
  31.         {
  32.          output +="1";
  33.          break;
  34.  
  35.         }
  36.         int tempBin = temp % 2;
  37.         char tempChar = tempBin+48;
  38.         output += tempChar;
  39.         temp = temp / 2;
  40.         len = GetNumberOfDigits(temp);
  41.  
  42.     }
  43.     reverseStr(output);
  44.     return output;
  45.  
  46. }
  47.  
  48.  
  49. int main()
  50. {
  51.   int n = 1001;
  52.   string outputNumber = decimalToBinary(n);
  53.   cout << "OUTPUT " << outputNumber << endl;
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement