Skip to content

Instantly share code, notes, and snippets.

@anxiousmodernman
Last active June 17, 2018 04:31
Show Gist options
  • Save anxiousmodernman/46c511b6d41dcb31de54b176ac8bb432 to your computer and use it in GitHub Desktop.
Save anxiousmodernman/46c511b6d41dcb31de54b176ac8bb432 to your computer and use it in GitHub Desktop.
hex conversion: hex string to integer
#include <stdio.h>
#include <ctype.h>
int htoi(char hex_string[]);
int expect(int got, int wanted);
void debuggerino(void);
int htoi(char hex_string[]) {
/* calculate len first and check for 0x offset */
int hex_offset = 0;
int len = 0;
for (int i = 0; hex_string[i] != '\0'; i++) {
if (i == 0 && hex_string[i] == '0')
hex_offset++;
if (i == 1 && tolower(hex_string[i]) == 'x')
hex_offset++;
len++;
}
int value = 0;
int start = hex_offset == 2 ? hex_offset : 0;
for (int i = start; i < len; i++) {
char c = tolower(hex_string[i]);
//printf("got %c %i\n", c, c);
if (c >= '0' && c <= '9') {
//printf("1-9 adding: %i\n", (c - 48) * (1 << (4*(len-1-i))));
value += (c - 48) * (1 << (4*(len-1-i)));
} else if (c >= 'a' && c <= 'f') {
//printf("a-f adding: %i\n", ((c - 'a') + 10) * (1 << (4*(len-1-i))));
value += ((c - 'a') + 10) * (1 << (4*(len-1-i)));
} else {
return -1; /* error */
}
}
return value;
}
int expect(int got, int wanted) {
if (got != wanted) {
printf("FAIL: got: %i wanted: %i\n", got, wanted);
return -1;
} else {
printf("PASS\n");
return 0;
}
}
void debuggerino() {
int len = 2;
int i = 1;
printf("'f' - 'a' : %i\n", ('f' - 'a'));
printf("('f' - 'a') + 10 : %i\n", (('f' - 'a') + 10));
printf("(('f' - 'a') + 10) * (1 << (4*(len-1-i))) : %i\n",
(('f' - 'a') + 10) * (1 << (4*(len-1-i))));
}
int main() {
//debuggerino();
//return 0;
expect(htoi("10"), 16);
expect(htoi("100"), 256);
expect(htoi("FF"), 255);
expect(htoi("Fe"), 254);
expect(htoi("0xFe"), 254);
expect(htoi("0XFe"), 254);
expect(htoi("0Xe3"), 227);
expect(htoi("0x00"), 0);
expect(htoi("0000000"), 0);
expect(htoi("100"), 256);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment