Skip to content

Instantly share code, notes, and snippets.

@gulan
Created November 17, 2016 17:34
Show Gist options
  • Select an option

  • Save gulan/0b0a5218147c6dbcd312a5d058269149 to your computer and use it in GitHub Desktop.

Select an option

Save gulan/0b0a5218147c6dbcd312a5d058269149 to your computer and use it in GitHub Desktop.
#include<assert.h>
#include<stdio.h>
/* htoi(): convert hext digit string to native int. */
/*
left-to-right recursive:
htoir("2") == 2
htoir("A") == 10
htoir("23") == 16*htoir("2") + 3
htoir("234") == 16*htoir("23") + 4 == 16*[16*htoir("2") + 3] + 4
*/
int
converth(char ch) {
int d;
switch (ch) {
case '0': d = 0; break;
case '1': d = 1; break;
case '2': d = 2; break;
case '3': d = 3; break;
case '4': d = 4; break;
case '5': d = 5; break;
case '6': d = 6; break;
case '7': d = 7; break;
case '8': d = 8; break;
case '9': d = 9; break;
case 'A': case 'a': d = 10; break;
case 'B': case 'b': d = 11; break;
case 'C': case 'c': d = 12; break;
case 'D': case 'd': d = 13; break;
case 'E': case 'e': d = 14; break;
case 'F': case 'f': d = 15; break;
default: d = -1; /* error */
}
return d;
}
/* right-to-left iterative*/
int
htoi(char s[]) {
int i = 0;
int n = 0;
int d;
d = converth(s[i]);
while (d != -1) {
n = 16 * n + d;
i++;
d = converth(s[i]);
}
return n;
}
int
main (int argc, char *argv[]) {
assert (htoi("0") == 0);
assert (htoi("9") == 9);
assert (htoi("A") == 10);
assert (htoi("a") == 10);
assert (htoi("00000000") == 0);
assert (htoi("10") == 16);
assert (htoi("19") == 25);
assert (htoi("1A") == 26);
assert (htoi("1a") == 26);
assert (htoi("100") == 256);
// printf("%d\n", htoi("FFFF"));
// printf("%d\n", htoi("FFFFFFFF"));
// printf("%d\n", htoi("FFFFFFFFFF")); /* overflow */
printf("PASS\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment