Got bored, wrote a C program.

I got bored so I did an exercise from The C Programming Language, exercise 2-3 to be exact:

 
#include <stdio.h>
int htoi(char s[]);
 
int main() {
  char hexNum[] = "0x43fa";
  char hexNum2[] = "0xfa";
  char hexNum3[] = "0xa";
  char hexNum4[] = "0x0";
  printf("The value %s converted to %d\n", hexNum, htoi(hexNum));
  printf("The value %s converted to %d\n", hexNum2, htoi(hexNum2));
  printf("The value %s converted to %d\n", hexNum3, htoi(hexNum3));
  printf("The value %s converted to %d\n", hexNum4, htoi(hexNum4));
  return 0;
}
 
int htoi(char s[]) {
  int i = 0,n = 0,t = 0;
 
  for(i = 0; s[i] != '\0'; i++) {
    t = 0;
    if(s[i] >= '0' && s[i] <= '9' && i != 0) {
      t = s[i] - '0';
      n = (16 * n) + t;
    } else if (s[i] >= 'a' && s[i] <= 'f') {
      t = 10 + (s[i] - 'a');
      n = (16 * n) + t;
    } else if (s[i] >= 'A' && s[i] <= 'F') {
      t = 10 + (s[i] - 'A');
      n = (16 * n) + t;
    }
  }
 
  return n;
}
Posted in C | Tagged