Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- #include <vector>
- #include <algorithm>
- using namespace std;
- void displayVector(vector <int> v){
- for(unsigned i=0; i<v.size(); i++){
- cout << v[i];
- }
- //cout << endl;
- }
- int main()
- {
- // 1. Intro
- menu:
- cout << "Give me a natural number (in decimal system) to convert it into binary:\n";
- double input;
- cin >> input;
- // 2. Convert to integer in case of error
- int n = int(fabs(input));
- int numOfDigits = int(log2(n)) + 1;
- //cout << numOfDigits << endl;
- //cout << "Logs: " << log(n) << " / " << log(2) << " = " << log(n) / log(2) << " ----> " << int(log(n) / log(2)) + 1 << endl;
- cout << "Decimal: " << n << endl;
- // 3. Check the case of 0 or the overflow case
- if(n == 0){
- cout << "Binary : 0 (No specified number of digits)" << endl << endl;
- goto menu;
- }
- if(n > 1000000000){
- cout << "Cannot make calculations with numbers higher than: " << 1000000000 << endl << endl;
- return -1000;
- }
- // 4. Search the digits
- vector <int> digits = vector <int> ();
- int sum = n;
- for(int i=numOfDigits-1; i>=0; i--){
- if(sum >= pow(2, i)){
- digits.push_back(1);
- sum -= pow(2, i);
- }
- else{
- digits.push_back(0);
- }
- }
- cout << "Binary : ";
- displayVector(digits);
- cout << " (" << numOfDigits << " digits)";
- cout << endl << endl;
- goto menu;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement