Last active
September 4, 2019 01:20
-
-
Save dgodfrey206/5bdffcb6654ee8003183707b51a7b038 to your computer and use it in GitHub Desktop.
Converting to and from hex
This file contains hidden or 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<bits/stdc++.h> | |
using namespace std; | |
string toHex(int n) { | |
string result; | |
while (n) { | |
int rem = n % 16; | |
result += (rem < 10) ? (rem + '0') : ('A' + rem - 10); | |
n /= 16; | |
} | |
reverse(result.begin(), result.end()); | |
return result; | |
} | |
int toDec(string hex) { | |
int result = 0; | |
for (size_t i=0; i<hex.size(); i++) { | |
char d = hex[hex.size() - i - 1]; | |
int p = 0; | |
if (isdigit(d)) { | |
p = d - '0'; | |
} else { | |
p = 10 + d - 'A'; | |
} else { | |
cout << "Something went wrong.\n"; | |
} | |
result += p * pow(16, i); | |
} | |
return result; | |
} | |
int main(){ | |
cout << ('B' - 'A' + 10); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment