Skip to content

Instantly share code, notes, and snippets.

@HyperPlay
Created August 28, 2019 01:02
Show Gist options
  • Save HyperPlay/e0e6b46b93e950dbcb06590036004222 to your computer and use it in GitHub Desktop.
Save HyperPlay/e0e6b46b93e950dbcb06590036004222 to your computer and use it in GitHub Desktop.
Console decimal to hexadecimal converter. (0123456789 to 0123456789ABCDEF)
#include <iostream>
#include <vector>
using std::cin, std::cout, std::endl, std::vector, std::string, std::atoi;
char single_hex(int dec);
bool is_whole_number(string s);
long long get_input();
int main() {
cout << "Console decimal to hexadecimal converter. (0123456789 to 0123456789ABCDEF)\n";
long long input = get_input();
vector<char> output;
long long last = input;
while (true) {
output.push_back(single_hex(input % 16));
input /= 16;
if (input == last) {
int start = output.size() - 1;
if (output.size() > 1 && output[start] == '0') start--;
for (int i = start; i >= 0; i--) {
cout << output[i];
}
cout << endl;
return 0;
} else {
last = input;
}
}
}
char single_hex(int dec) {
dec %= 16;
switch (dec) {
case 0:
return '0';
case 1:
return '1';
case 2:
return '2';
case 3:
return '3';
case 4:
return '4';
case 5:
return '5';
case 6:
return '6';
case 7:
return '7';
case 8:
return '8';
case 9:
return '9';
case 10:
return 'a';
case 11:
return 'b';
case 12:
return 'c';
case 13:
return 'd';
case 14:
return 'e';
case 15:
return 'f';
}
return '\0'; //prevents compiler warning.
}
bool is_whole_number(string s) {
for (int i = 0; i < s.length(); i++) {
if (s[i] == '-') continue;
if (!isdigit(s[i])) return false;
}
return true;
}
long long get_input() {
cout << "Input an integer for conversion: ";
validate:
string sinput;
cin >> sinput;
while (!is_whole_number(sinput)) {
cout << "Input must be an integer!\nInput an integer for conversion: ";
cin >> sinput;
}
long long input = atoll(sinput.c_str());
if (input < 0) {
cout << "Input must be greater than 0!\nInput a new integer for conversion: ";
goto validate;
}
return input;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment