Skip to content

Instantly share code, notes, and snippets.

@cntrump
Last active May 10, 2022 08:05
Show Gist options
  • Save cntrump/9c22ad81983a554d22448e4b9dfd2ede to your computer and use it in GitHub Desktop.
Save cntrump/9c22ad81983a554d22448e4b9dfd2ede to your computer and use it in GitHub Desktop.
Convert hex string to number.
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;
}
@cntrump
Copy link
Author

cntrump commented May 7, 2022

Test

char num[] = "24292a";
str2hex(num, sizeof(num));

char a[] = "f6f8fa";
str2hex(a, sizeof(a));

char A[] = "FFFFFF";
str2hex(A, sizeof(A));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment