Created
July 22, 2018 09:43
-
-
Save mnemocron/3d1924fb49a12e095bf9f1bca4565cc9 to your computer and use it in GitHub Desktop.
Converts a String in hexadecimal to an Integer
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
uint32_t htoi( String htoi_str ){ | |
char itoh_lower[18] = {"0123456789abcdef"}; // 16 chars + null | |
char itoh_upper[18] = {"0123456789ABCDEF"}; // 16 chars + null | |
uint32_t htoi_number = 0; | |
for(int index = 0; index < htoi_str.length(); index ++){ // each hex number in String | |
for(int val = 0; val < 16; val ++){ // each possible value | |
if ( htoi_str[htoi_str.length() -index -1] == itoh_lower[val] || | |
htoi_str[htoi_str.length() -index -1] == itoh_upper[val] ){ | |
if(val > 0){ | |
// htoi_number += val * power(16, index); | |
htoi_number += (uint32_t)( val * (power(16, index) + 0.01) ); | |
} | |
} | |
} | |
} | |
return (uint32_t)(htoi_number); | |
} | |
/*#################################################################################################*/ | |
// alternative version without double to uint32_t conversation | |
uint32_t htoi( String htoi_str ){ | |
char itoh_lower[18] = {"0123456789abcdef"}; // 16 chars + null | |
char itoh_upper[18] = {"0123456789ABCDEF"}; // 16 chars + null | |
uint32_t htoi_number = 0; | |
for(int index = 0; index < htoi_str.length(); index ++){ // each hex number in String | |
for(int val = 0; val < 16; val ++){ // each possible value | |
if ( htoi_str[htoi_str.length() -index -1] == itoh_lower[val] || | |
htoi_str[htoi_str.length() -index -1] == itoh_upper[val] ){ | |
if(val > 0){ | |
htoi_number += val * power(16, index); | |
} | |
} | |
} | |
} | |
return (uint32_t)(htoi_number); | |
} | |
// because pow() is of type double and conversation from double to unit32_t is lossy | |
uint32_t power(int p_base, int p_exp){ | |
uint32_t pow_ret = 1; | |
for(int p_ctr = 0; p_ctr < p_exp; p_ctr ++){ | |
pow_ret *= p_base; | |
} | |
return pow_ret; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment