Advertisement
Skirtek

Untitled

Mar 21st, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. string dec_to_bin(const int number)
  7. {
  8.     if (number == 0 || number == 1)
  9.     {
  10.         return number == 0 ? "0" : "1";
  11.     }
  12.  
  13.     return number % 2 == 0 ? dec_to_bin(number / 2) + "0" : dec_to_bin(number / 2) + "1";
  14. }
  15.  
  16. string complete(string binary)
  17. {
  18.     while (binary.length() < 8)
  19.     {
  20.         binary.insert(0, "0");
  21.     }
  22.  
  23.     return binary;
  24. }
  25.  
  26. int bin_to_dec(string binary)
  27. {
  28.     const int length = binary.length();
  29.     auto sum = 0;
  30.     auto power = 1;
  31.  
  32.     for (auto i = length - 1; i >= 0; i--)
  33.     {
  34.         sum += (binary[i] - 48)*power;
  35.         power *= 2;
  36.     }
  37.  
  38.     return sum;
  39. }
  40.  
  41. int main()
  42. {
  43.     int number;
  44.     cout << "Wprowadz liczbe dziesietna:" << endl;
  45.     cin >> number;
  46.  
  47.     if (cin.fail() || number < 0) {
  48.         cout << "Podales zla liczbe" << endl;
  49.         return 0;
  50.     }
  51.  
  52.     cout << "Ta liczba binarnie to: " << endl;
  53.     string binary = complete(dec_to_bin(number));
  54.     cout << binary << endl;
  55.  
  56.     cout << "Ta liczba decymalnie to:" << endl;
  57.     cout << bin_to_dec(binary);
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement