Last active
October 17, 2024 06:39
-
-
Save jamesy0ung/42487ff0366f8dc69c08e19355289f9b to your computer and use it in GitHub Desktop.
Decimal to Binary
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 <vector> | |
#include <string> | |
#include <limits> | |
#include <stdexcept> | |
int main() | |
{ | |
std::string input; | |
unsigned long long num; | |
int remainder { 0 }; | |
std::vector<int> binary; | |
std::cout << "Positive Number to Binary Converter\n"; | |
std::cout << "Enter a number: "; | |
while (true) | |
{ | |
std::cin >> input; | |
if (input.find_first_not_of("0123456789") != std::string::npos) | |
{ | |
std::cout << "Invalid input. Please enter a valid number: "; | |
continue; | |
} | |
try | |
{ | |
num = std::stoull(input); | |
break; | |
} | |
catch (const std::out_of_range&) | |
{ | |
std::cout << "Number out of range for a 64-bit unsigned integer. Please enter a valid number: "; | |
} | |
catch (const std::invalid_argument&) | |
{ | |
std::cout << "Invalid input. Please enter a valid number: "; | |
} | |
} | |
std::cout << std::endl; | |
if (num == 0) | |
{ | |
std::cout << "The binary representation is 0"; | |
} | |
else | |
{ | |
binary.clear(); | |
while (num > 0) | |
{ | |
remainder = num % 2; | |
num = num / 2; | |
binary.push_back(remainder); | |
} | |
std::cout << "The binary representation is: "; | |
for (int i = binary.size() - 1; i >= 0; i--) | |
{ | |
std::cout << binary[i]; | |
} | |
std::cout << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment