Last active
October 29, 2017 19:49
-
-
Save tapoton/f09c9e447c0e5ada174da2dbf0258dde to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <cmath> | |
using namespace std; | |
class LongLong { | |
long left; | |
unsigned long right; | |
bool isNegative() { | |
bool isNegative = (left & (1 << 31)) > 0; //0b10000000000000000000000000000000 | |
return isNegative; | |
} | |
public: | |
LongLong(string x) { | |
bool isNegative = x[0] == '-'; | |
int offset = isNegative ? 1 : 0; | |
long left = 0; | |
unsigned long right = 0; | |
unsigned long decimal_length = x.length() - offset; | |
// digits – массив цифр исходного числа | |
// конвертируем строку в массив цифр | |
char *digits = new char[decimal_length]; | |
for (int i = 0; i < decimal_length; i++) { | |
digits[i] = x[i + offset] - '0'; | |
} | |
// конвертируем число digits в двоичное представление. | |
// Первые 32 цифры записываем в right, следующую 31 цифру – в left | |
int position = 0; | |
while (decimal_length > 0) { | |
int offset = (digits[0] < 2) ? 1 : 0; | |
unsigned long new_decimal_length = decimal_length - offset; | |
// new_digits – массив цифр результата деления (digits / 2) | |
char *new_digits = new char[new_decimal_length]; | |
// remainder – остаток от деления (digits / 2) | |
int remainder = offset; | |
for (int i = 0; i < decimal_length - offset; i++) { | |
int dividend = remainder * 10 + digits[i + offset]; | |
new_digits[i] = dividend / 2; | |
remainder = dividend % 2; | |
} | |
if (position < 32) { | |
right = right | remainder * (1 << position); | |
} else { | |
left = left | remainder * (1 << (position - 32)); | |
} | |
digits = new_digits; | |
decimal_length = new_decimal_length; | |
position++; | |
} | |
if (isNegative) { | |
left = left | (1 << 31); | |
} | |
this -> left = left; | |
this -> right = right; | |
} | |
string binary_description() { | |
string descr = ""; | |
unsigned long t_right = right; | |
for (int i = 0; i < 32; i++) { | |
descr.insert(0, t_right % 2 ? "1" : "0"); | |
t_right /= 2; | |
} | |
long t_left = left; | |
for (int i = 0; i < 32; i++) { | |
descr.insert(0, t_left % 2 ? "1" : "0"); | |
t_left /= 2; | |
} | |
return descr; | |
} | |
}; | |
int main(int argc, const char * argv[]) { | |
while (true) { | |
string s; | |
cin >> s; | |
LongLong n(s); | |
cout << n.binary_description() << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment