DEV Community

Cover image for Hex to Integer
Senthil Kumaran
Senthil Kumaran

Posted on

Hex to Integer

https://www.learntosolveit.com/ is my project that helped me become a software engineer. I continue to work on this fundamental project to help myself and others become good programmers. The project now is a companion website to learn C programming using K&R book. It uses modern tools, and is designed to be used along with the book.

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>

#define MAXLINE 100
#define BASE 16

int mgetline(char line[], int lim);

unsigned int htoi(const char s[], int len);

int main(void) {
    char line[MAXLINE];
    int len;
    unsigned int value;

    len = mgetline(line, MAXLINE);
    value = htoi(line, len);

    printf("The value of %s is %u \n", (char *) line, value);

    return 0;
}

int mgetline(char line[], int lim) {
    int c, i;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        line[i] = (char) c;

    line[i] = '\0';

    return i;
}

unsigned int htoi(const char s[], int len) {
    int digit;
    int power = 1;
    unsigned int result = 0;
    int end_index = 0;

    if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
        end_index = 2;
    }

    for(int i=len-1; i>=end_index; i--) {
        if (s[i] >= '0' && s[i] <= '9') {
            digit = (s[i] - '0');
        } else if (s[i] >= 'a' && s[i] <= 'f') {
            digit = (s[i] - 'a') + 10;
        } else if (s[i] >= 'A' && s[i] <= 'F') {
            digit = (s[i] - 'A') + 10;
        }
        result += digit * power;
        power *= BASE;
    }

    return result;
}
Enter fullscreen mode Exit fullscreen mode

Example output

$ ./a.out
DEADBEEF
The value of DEADBEEF is 3735928559
$ ./a.out
0xDEADBEEF
The value of 0xDEADBEEF is 3735928559
Enter fullscreen mode Exit fullscreen mode

Review the discussions and analysis of the program here
https://www.learntosolveit.com/cprogramming/chapter2/ex_2.3_htoi

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas

You know that strtoull(3) exists, right?

Collapse
 
orsenthil profile image
Senthil Kumaran

Yes. These exercises from book are learning exercises. In real world programs, I will use strtoull.