Last active
May 10, 2022 08:05
-
-
Save cntrump/9c22ad81983a554d22448e4b9dfd2ede to your computer and use it in GitHub Desktop.
Convert hex string to number.
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
int str2hex(char *str, int len) { | |
len = MIN(len, 8); | |
int hex = 0; | |
int bit = 0; | |
for (int i = len - 1; i >= 0; i--) { | |
int n; | |
char ch = str[i]; | |
if (ch >= '0' && ch <= '9') { | |
n = ch - '0'; | |
} else if (ch >= 'A' && ch <= 'F') { | |
n = 0xa + ch - 'A'; | |
} else if (ch >= 'a' && ch <= 'f') { | |
n = 0xa + ch - 'a'; | |
} else if (ch == '\0') { | |
continue; | |
} else { | |
break; | |
} | |
hex |= n << bit; | |
bit += 4; | |
} | |
return hex; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test