0

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.

5
  • 3
    Is this homework or why do you want to do it without using a library function? Commented Jun 3, 2011 at 21:13
  • How is FE257469 a 32-bit number? If each character is ASCII, then each character would be 7/8 bits.. Commented Jun 3, 2011 at 21:15
  • @Colin FE257469 is 4263867497 decimal. Commented Jun 3, 2011 at 21:16
  • :) No guys, it's not. I know that it sounds fairly simple but I just wondered if there is an easy way of doing this (I can't really think clearly at the moment after so many hours of studying!) Commented Jun 3, 2011 at 21:23
  • @Colin strictly speaking is not a 32-bit number but it represents a 32-bit number, that's what I meant Commented Jun 3, 2011 at 21:24

2 Answers 2

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.