Slogging through C
by Alex
Compared to the other languages I’ve learned before (Ruby, Java and Actionscript), C is pretty tricky. Thankfully, The C Programming Language by Kernighan and Ritchie is a great book and makes it less of a pain.
When given a seemingly trivial problem like writing a hex to decimal converter, I could probably crank out a couple line of Ruby without much hassle. Ruby even has a converter written into its standard library. However in C, things aren’t as simple. Due to my relative inability, it took me most of an afternoon to hack together a working solution.
#include <stdio.h> #include <string.h> int power(int e) { int i, n; n = 1; for (i = 0; i < e; ++i) n = n * 16; return n; } //hex to int, given char array of hex string s int htoi(char s[]) { int l = strlen(s); // -1 comes from excluding \0 char int i, n; n = 0; for (i = 0; (s[i] >= '0' && s[i] <= '9') || (s[i] >= 'A' && s[i] <= 'F'); ++i) { //loop as long as char is int of A-F if (s[l-i-1] >= '0' && s[l-i-1] <= '9') { n += power(i) * (s[l-i-1] - '0'); } else { n += power(i) * (s[l-i-1] - 'A' + 10); //sets base at A, and then +10 considering A = 10 } } return n; } int main() { //test cases char h1[] = "A0"; char h2[] = "4235"; char h3[] = "BF4334"; char h4[] = "AAFF47"; printf("%d \t %d \t %d \t %d\n", htoi(h1), htoi(h2), htoi(h3), htoi(h4)); return 0; }
I’m scared for when I get to pointers.
Comments
Hi,
when using The C Programming Language to learn C, be careful to take the second edition from ‘88 or later.
The first is not ANSI-C, which is the defacto standard most compilers and platforms support.
Cheers,
Ruben
I am using the second version. Thanks for your concern though.
I’ve also come to understand that there are some differences between ANSI-C and C99. Will I run into any problems because of this?
Hello World.