Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- string dec_to_bin(const int number)
- {
- if (number == 0 || number == 1)
- {
- return number == 0 ? "0" : "1";
- }
- return number % 2 == 0 ? dec_to_bin(number / 2) + "0" : dec_to_bin(number / 2) + "1";
- }
- string complete(string binary)
- {
- while (binary.length() < 8)
- {
- binary.insert(0, "0");
- }
- return binary;
- }
- int bin_to_dec(string binary)
- {
- const int length = binary.length();
- auto sum = 0;
- auto power = 1;
- for (auto i = length - 1; i >= 0; i--)
- {
- sum += (binary[i] - 48)*power;
- power *= 2;
- }
- return sum;
- }
- int main()
- {
- int number;
- cout << "Wprowadz liczbe dziesietna:" << endl;
- cin >> number;
- if (cin.fail() || number < 0) {
- cout << "Podales zla liczbe" << endl;
- return 0;
- }
- cout << "Ta liczba binarnie to: " << endl;
- string binary = complete(dec_to_bin(number));
- cout << binary << endl;
- cout << "Ta liczba decymalnie to:" << endl;
- cout << bin_to_dec(binary);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement