Skip to content

Instantly share code, notes, and snippets.

@AeroStun
Last active December 9, 2017 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AeroStun/e95e346c606318dddf54136ad8d955c6 to your computer and use it in GitHub Desktop.
Save AeroStun/e95e346c606318dddf54136ad8d955c6 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <cmath>
int find_exp(int dec){
#ifndef __GNUG__
int n = 0;
for(int be = 0; dec >= be; ++n){
be = 1 << (4 * (n + 1));
}
return n - 1;
#else
return (7 - __builtin_clz(dec) / 4);
#endif
}
char conv_to_letter(int num){
return num + (num > 9 ? 55 : 48);
}
std::string tohex(int integer){
std::string ret{};
div_t d{0, integer};
for(int i = find_exp(integer); i >= 0; --i){
d = std::div(d.rem, (1 << (4 * i)));
ret.push_back(conv_to_letter(d.quot));
}
return ret;
}
int main(){
std::cout << "Enter a number you want in hex: " << std::flush;
int integer;
std::cin >> integer;
std::cout << integer << "(10) = " << tohex(integer) << "(16)\n" << std::flush;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment