简体   繁体   中英

Convert a string of hexadecimal digits into integer

I am trying to implement the htoi(s) [Dennis Ritchie chapter2 exercise 2-3 Q] which converts a string of hexadecimal digits, into its equivalent integer, can anyone help me out in the logic of this program, i dont need the code, i just need the logic for implementing it. I am not able to get the correct logic

Let's take a step back:

How would you implement a function that accepts a single hex digit and returns it's decimal equivalent?

In other words, how would you write this function:

unsigned int hextodec(char c)
{
    ... your code here
}

Hint: for decimal digits what happens when you calculate c -'0' ?

Once you have this function it should be fairly easy to use it to calculate the conversion of longer hex strings.

Hint: 0xF is 15 and 0x10 is 16

Use the strtol function with base 16.

About this way:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int xstrtol16(const char *s)
{
    errno = 0;
    char *endp = NULL;
    int result = strtol(s, &endp, 16);

    if (*charp || errno) {
       fprintf(stderr, "Failed to convert...\n");
       exit(1);
    }

    return result;
}

Think about what a printable number (in any base) is. Basically a list of symbols which represent simple numeric values (0...base-1), and associated "weights" of their digit positions. For decimal the symbols are "0123456789" and the weights are 1, 10 , 100, 1000...

You convert the printable number into "integer" by finding the corresponding numeric value of each symbol, multiplying it times the weight for that digit position, and summing those products together. There are tricks to doing this efficiently, but a straight-forward "dumb" implementation can get the job done perfectly well.

Hex is slightly complicated because there are two runs of symbols -- 0-9 and AF -- and it's sometimes desired to accept both upper-case and lower-case letters. There are again tricks to handling this, but doing it in a straight-forward fashion (compare each character to the limits of each run and decide which one it fits) is perfectly fine (and more general than other approaches). You can also even use a index op, where you simply find the character's index into "0123456789ABCDEF" -- inefficient but simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM