Skip to content

Instantly share code, notes, and snippets.

@iamarkdev
Created December 1, 2016 11:22
Show Gist options
  • Save iamarkdev/5c734deda28625e41cc0e5de7eb06f90 to your computer and use it in GitHub Desktop.
Save iamarkdev/5c734deda28625e41cc0e5de7eb06f90 to your computer and use it in GitHub Desktop.
Hex string to integer
#include <stdio.h>
long hexToInt(char hexString[]) {
long result = 0;
for (int i = 0; hexString[i] != '\0'; i++) {
if ((hexString[i] == '0' && hexString[i + 1] == 'x') || hexString[i] == 'x') {
continue;
}
int value = 0;
if (hexString[i] >= '0' && hexString[i] <= '9') {
value = hexString[i] - '0';
} else if (hexString[i] >= 'a' && hexString[i] <= 'z') {
value = (hexString[i] - 'a') + 10;
} else if (hexString[i] >= 'A' && hexString[i] <= 'Z') {
value = (hexString[i] - 'A') + 10;
}
result = result * 16 + value; // multiply by 16 for correct digit shifting because we're iterating left to right.
}
return result;
}
int main() {
long result = hexToInt("0xabcdef");
printf("%ld\n", result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment