tags:

views:

99

answers:

3

I need to convert ASCII to HEX and HEX to ASCII by using a C program, how can I do that?

A: 

Well, this seems to be what you're looking for (hex to ASCII): http://snippets.dzone.com/posts/show/2073 , should be easily reversible.

Piskvor
(btw, this is the 4th result when searching "hex to ascii c")
Piskvor
+1  A: 

Its pretty easy. Scan through character by character ... best to start from the end. If the character is a number between 0 and 9 or a letter between a and f then place it in the correct position by left shifting it by the number of digits you've found so far.

For converting to a string then you do similar but first you mask and right shift the values. You then convert them to the character and place them in the string.

Goz
+1  A: 

Here's a simplistic function to convert one character to a hexadecimal string.

char hexDigit(unsigned n)
{
    if (n < 10) {
        return n + '0';
    } else {
        return n + 'A';
    }
}

void charToHex(char c, char hex[3])
{
    hex[0] = hexDigit(c / 0x10);
    hex[1] = hexDigit(c % 0x10);
    hex[2] = '\0';
}
Eddie Sullivan