Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Exercise 2-3.
- * Write a function htoi(s), which converts a string of hexadecimal digits
- * (including an optional 0x or 0X) into its equivalent integer value.
- * The allowable digits are 0 through 9, a through f, and A through F.
- */
- #include <stdio.h>
- int
- h_to_i(const char* s) {
- int i = 0;
- int ret = 0;
- if (s[i] == '0')
- i++;
- if (i && (s[i] == 'x' || s[i] == 'X'))
- i++;
- while (s[i]) {
- if (s[i] >= '0' && s[i] <= '9')
- ret = ret * 16 + s[i] - '0';
- else if (s[i] >= 'a' && s[i] <= 'f')
- ret = ret * 16 + s[i] - 'a' + 10;
- else if (s[i] >= 'A' && s[i] <= 'F')
- ret = ret * 16 + s[i] - 'A' + 10;
- else
- return -1;
- i++;
- }
- return ret;
- }
- int
- main(int argc, char** argv) {
- printf("htoi(%s) = %d\n",argv[1], h_to_i(argv[1]));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment