limp
limp

Reputation: 919

Converting an ASCII number to a Hex number in C without using library functions

I want to convert an 32-bit ASCII number (e.g. "FE257469") to the equivalent 32-bit hex number which will be stored on a 32-bit variable. Most importnatly, I want to do that without using any library function like sscanf(), atoi(), etc.

Any ideas on that?

Thank in advance.

Upvotes: 0

Views: 4291

Answers (2)

x4u
x4u

Reputation: 14077

Here is an implementation of such a function based on a switch:

unsigned int parseHex( char *str )
{
    unsigned int value = 0;

    for(;; ++str ) switch( *str )
    {
        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
            value = value << 4 | *str & 0xf;
            break;
        case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
        case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
            value = value << 4 | 9 + *str & 0xf;
            break;
        default:
            return value;
    }
}

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490148

The usual way is something like:

initialize result to 0

  1. convert one digit of input to decimal to get current digit
  2. multiply result by 16
  3. add current digit to result
  4. repeat steps 1-3 for remaining digits

Upvotes: 1

Related Questions