tags:

views:

12133

answers:

9

In C what is the most efficient way to convert a hexadecimal value to its base 10 value?

For example, if I have FFFFFFFE the result would be 4294967294.

+15  A: 

You want strtol. The page explains it well.

Patrick
+3  A: 

Try this:

#include <stdio.h>
main()
{
    char s[] = "fffffffe";
    int x;
    sscanf(s, "%x", &x);
    printf("%u\n", x);
}
Mark Harrison
A: 

@Eric

Why is a code solution that works getting voted down? Sure, it's ugly and might not be the fastest way to do it, but it's more instructive that saying "strtol" or "sscanf". If you try it yourself you will learn something about how things happen under the hood.

I don't really think your solution should have been voted down, but my guess as to why it's happening is because it's less practical. The idea with voting is that the "best" answer will float to the top, and while your answer might be more instructive about what happens under the hood (or a way it might happen), it's definitely not the best way to parse hex numbers in a production system.

Again, I don't think there's anything wrong with your answer from an educational standpoint, and I certainly wouldn't (and didn't) vote it down. Don't get discouraged and stop posting just because some people didn't like one of your answers. It happens.

I doubt my answer makes you feel any better about yours being voted down, but I know it's especially not fun when you ask why something's being voted down and no one answers.

Derek Park
-1 Theres a reason we have comments...
mathepic
In August 2008 the site was brand new and *comments were not implemented*.
Derek Park
A: 

@Eric

I was actually hoping to see a C wizard post something really cool, sort of like what I did but less verbose, while still doing it "manually".

Well, I'm no C guru, but here's what I came up with:

unsigned int parseHex(const char * str)
{
    unsigned int val = 0;
    char c;

    while(c = *str++)
    {
        val <<= 4;

        if (c >= '0' && c <= '9')
        {
            val += c & 0x0F;
            continue;
        }

        c &= 0xDF;
        if (c >= 'A' && c <= 'F')
        {
            val += (c & 0x07) + 9;
            continue;
        }

        errno = EINVAL;
        return 0;
    }

    return val;
}

I originally had more bitmasking going on instead of comparisons, but I seriously doubt bitmasking is any faster than comparison on modern hardware.

Derek Park
Four complaints: 1) It does not compile. 2) Id does not handle lower case 3) It does not work (A => 1). 4) Invalid characters are just ignored!. Did you test it?
Martin York
Did you read it? "I didn't actually compile this, so I could have made some pretty big mistakes." So no, I didn't test it.
Derek Park
Derek Park
Roland Illig
+1  A: 

For larger Hex strings like in the example I needed to use strtoul.

+2  A: 

Why is a code solution that works getting voted down? Sure, it's ugly ...

Perhaps because as well as being ugly it isn't educational and doesn't work. Also, I suspect that like me, most people don't have the power to edit at present (and judging by the rank needed - never will).

The use of an array can be good for efficiency, but that's not mentioned in this code. It also takes no account of upper and lower case so it does not work for the example supplied in the question. FFFFFFFE

itj
A: 

If you don't have the stdlib then you have to do it manually.

unsigned long hex2int(char *a, unsigned int len)
{
    int i;
    unsigned long val = 0;

    for(i=0;i<len;i++)
       if(a[i] <= 57)
     val += (a[i]-48)*(1<<(4*(len-1-i)));
       else
     val += (a[i]-55)*(1<<(4*(len-1-i)));
    return val;
}

Note: This code assumes uppercase A-F. It does not work if len is beyond your longest integer 32 or 64bits, and there is no error trapping for illegal hex characters.

A: 

Noobs... this currently only works with lower case but its super easy to make it work with both.

cout << "\nEnter a hexadecimal number: ";
cin >> hexNumber;
orighex = hexNumber;

strlength = hexNumber.length();

for (i=0;i<strlength;i++)
{
    hexa = hexNumber.substr(i,1);
    if ((hexa>="0") && (hexa<="9"))
    {
        //cout << "This is a numerical value.\n";
    }
    else
    {
        //cout << "This is a alpabetical value.\n";
        if (hexa=="a"){hexa="10";}
        else if (hexa=="b"){hexa="11";}
        else if (hexa=="c"){hexa="12";}
        else if (hexa=="d"){hexa="13";}
        else if (hexa=="e"){hexa="14";}
        else if (hexa=="f"){hexa="15";}
        else{cout << "INVALID ENTRY! ANSWER WONT BE CORRECT\n";}
    }
    //convert from string to interger

    hx = atoi(hexa.c_str());
    finalhex = finalhex + (hx*pow(16.0,strlength-i-1));
}
cout << "The hexadecimal number: " << orighex << " is " << finalhex << " in decimal.\n";
Adam B.
+1  A: 

As if often happens, your question suffers from a serious terminological error/ambiguity. In common speech it usually doesn't matter, but in the context of this specific problem it is critically important.

You see, there's no such thing as "hex value" and "decimal value" (or "hex number" and "decimal number"). "Hex" and "decimal" are properties of representations of values. Meanwhile, values (or numbers) by themselves have no representation, so they can't be "hex" or "decimal". For example, 0xF and 15 in C syntax are two different representations of the same number.

I would guess that your question, the way it is stated, suggests that you need to convert ASCII hex representation of a value (i.e. a string) into a ASCII decimal representation of a value (another string). One way to do that is to us an integer representation as an intermediate one: first, convert ASCII hex representation to an integer of sufficient size (using functions from strto... group, like strtol), then convert the integer into the ASCII decimal representation (using sprintf).

If that's not what you need to do, then you have to clarify your question, since it is impossible to figure it out from the way your question is formulated.

AndreyT