Created
July 19, 2015 05:31
-
-
Save alekratz/22684063b1a01e893cd5 to your computer and use it in GitHub Desktop.
parses multiple radices using C++11 and some boost
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
template<typename T> | |
T parse_radix(const std::string& str, i32 radix) | |
{ | |
assert("provided radix is not between the supported range of 2 and 36" && radix >= 2 && radix <= 36); | |
T result = 0; | |
auto get_radix_map = [](i32 radix) -> std::map<char, T> | |
{ | |
typedef std::pair<char, T> pair_t; | |
std::map<char, T> result; | |
if(radix <= 10) | |
{ | |
for(int i = 0; i < radix; i++) | |
result.insert(pair_t('0' + i, i)); | |
} | |
else if(radix <= 36) | |
{ | |
for(int i = 0; i < 10; i++) | |
result.insert(pair_t('0' + i, i)); | |
for(int i = 0; i < (radix - 10); i++) | |
result.insert(pair_t('a' + i, i + 10)); | |
} | |
return result; | |
}; | |
auto radix_map = get_radix_map(radix); | |
for(const char& c : str) | |
{ | |
result *= radix; | |
result += radix_map[c]; | |
} | |
return result; | |
} | |
template<typename T> | |
T parse_explicit_radix(const std::string& str) | |
{ | |
T result = 0; | |
i32 radix = 0; | |
std::string parse; | |
if(boost::starts_with(str, "0b")) | |
{ | |
radix = 2; | |
parse = str.substr(2); | |
} | |
else if(boost::starts_with(str, "0x")) | |
{ | |
radix = 16; | |
parse = str.substr(2); | |
} | |
else if(boost::starts_with(str, "0")) | |
{ | |
radix = 8; | |
parse = str.substr(1); | |
} | |
else | |
{ | |
radix = 10; | |
parse = str; | |
} | |
return parse_radix<T>(str, radix); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment