Skip to content

Instantly share code, notes, and snippets.

@krysseltillada
Created January 8, 2016 18:58
Show Gist options
  • Save krysseltillada/33251f605eb87ef3b456 to your computer and use it in GitHub Desktop.
Save krysseltillada/33251f605eb87ef3b456 to your computer and use it in GitHub Desktop.
exercise 2-3 (the c programming language 2nd ed) hexadecimal constant strings to decimal
#include <stdio.h>
int getLength (char s[]) {
int sz = 0;
for (; s[sz] != '\0'; ++sz);
return sz;
}
int pow (int c, int n) {
int i = 0, v = 1;
if (n == 0)
return 1;
for (; i < n; ++i)
v *= c;
return v;
}
int toInt (char c) {
return c - '0';
}
char clower(int c) {
if (c >= 'A' && c <= 'Z')
return c + 'a' - 'A';
return c;
}
int htoi (char cStr[]) {
int ind = 0, m = 0, state = 1;
int vInt = 0;
if (cStr[ind] == '0') {
if ( clower(cStr[ind + 1]) >= 'a' && clower(cStr[ind + 1]) <= 'w' ||
clower(cStr[ind + 1]) == 'y' || clower(cStr[ind + 1]) == 'z' ) {
return 0;
}
else if (clower(cStr[ind + 1]) == 'x') {
for (ind = getLength(cStr) - 1; ind >= 2; --ind) {
if (clower(cStr[ind]) >= 'a' && clower(cStr[ind]) <= 'f') {
vInt += pow (16, m) * (clower(cStr[ind]) - 102 + 15);
++m;
}
else if (cStr[ind] >= '0' && cStr[ind] <= '9') {
vInt += pow (16, m) * toInt (cStr[ind]);
++m;
}
}
state = 0;
}
}
if (state) {
for (ind = getLength(cStr); ind >= 0; --ind) {
if (clower(cStr[ind]) >= 'a' && clower(cStr[ind]) <= 'f') {
vInt += pow (16, m) * (clower(cStr[ind]) - 102 + 15);
++m;
}
else if (cStr[ind] >= '0' && cStr[ind] <= '9') {
vInt += pow (16, m) * toInt (cStr[ind]);
++m;
}
}
}
return vInt;
}
int main ()
{
printf ("\n%d", htoi("0x1a"));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment