Advertisement
Guest User

Untitled

a guest
Mar 24th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cmath>
  4. using namespace std;
  5. class Binary {
  6.     bool data[32];
  7.     int number;
  8. public:
  9.     Binary();
  10.     Binary(int value);
  11.     Binary(string s);
  12.     void show() const;
  13.     int to_int() const;
  14.     void bin(int n);
  15.     void string_to_bin(string s);
  16. };
  17. void Binary::string_to_bin(string s) {
  18.     for (int i = 0; i < s.length(); i++) {
  19.         if (s[i] == '1') {
  20.             data[i] = 1;
  21.         }
  22.         else {
  23.             data[i] = 0;
  24.         }
  25.     }
  26. }
  27. void Binary::bin(int n) {
  28.     if (n >= 2) {
  29.         bin(n / 2);
  30.     }
  31.     number++;
  32. }
  33. Binary::Binary() {
  34.     number = 0;
  35.     for (int i = 0; i < 32; i++) {
  36.         data[i] = 0;
  37.     }
  38. }
  39. Binary::Binary(int value) {
  40.     number = 0;
  41.     bin(value);
  42.     for (int i = number - 1; i >= 0; i--) {
  43.         data[i] = value % 2;
  44.         value /= 2;
  45.     }
  46. }
  47. Binary::Binary(string s) {
  48.     number = s.length();
  49.     string_to_bin(s);
  50. }
  51. void Binary::show() const {
  52.     for (int i = 0; i < number; i++) {
  53.         cout << data[i];
  54.     }
  55. }
  56. int Binary::to_int() const {
  57.     int a = 0;
  58.     for (int i = number-1; i >= 0; i--) {
  59.         a += data[i] * pow(2, i);
  60.     }
  61.     return a;
  62. }
  63. int main() {
  64.     int n;
  65.     cin >> n;
  66.     Binary bin(n);
  67.     bin.show();
  68.     system("pause");
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement