0

In C I'm reading a string from a txt file, for example the string "hello", so i have my:

F=fopen("text.txt","r");
fscanf(F,"%s\n",string);

Now, if i want to convert this string to hex and decimal, i can do something like this:

for (i=0; i<strlen(string); i++)
{
   sprintf(st, "%02X", string[i]);  //Convert to hex
   strcat(hexstring, st);

   sprintf(st, "%03d", string[i]);  //Convert to dec
   strcat(decstring, st);
}

Now, my question is: i want to do the inverse operation, but how? This is the output if i convert "hello"

   hex-> 68656c6c6f
   dec-> 104101108108111

From "68656c6c6f" or "104101108108111" i want to go back to "hello", how can i do this?

(basically i want to do something like this website: http://string-functions.com/; String To Hex Converter, Hex To String Converter, Decimal To Hex, Converter, Hex To Decimal Converter)

Denilson Amorim
  • 9,642
  • 6
  • 27
  • 31
  • [This](http://stackoverflow.com/questions/5290089/how-to-convert-a-number-to-string-and-vice-versa-in-c) question may help you get where you're needing to go. – Rein S May 13 '15 at 21:13
  • for converting hex to string, see [this SO answer](http://stackoverflow.com/a/24337143/3723423) – Christophe May 13 '15 at 21:16

1 Answers1

0

The challenge is to realize you have a string of hex and a string of decimal, meaning you have a character string representation of the values, not the values themselves. So you will need to convert the string representations to the appropriate numeric values before converting back to the original string.

Presuming you have hex as a string representation of two-byte hex character pairs, the following will return the original string hello from 68656c6c6f:

/* convert hex string to original */
char hex2str[80] = {0};
char *p = hex2str;
int i = 0;
int itmp = 0;

while (hex[i])
{
    sscanf (&hex[i], "%02x", &itmp);
    sprintf (p, "%c", itmp);
    p++;
    i+=2;
}
*p = 0;

printf ("\n hex2str: '%s'\n\n", hex2str);

Output

$ ./bin/c2h2c < <(printf "hello\n")

 hex2str: 'hello'

Short Working Example

#include <stdio.h>
#include <string.h>

#define MAXS 64

int main (void) {

    char hex[] = "68656c6c6f";
    char hex2str[MAXS] = {0};
    char *p = hex2str;
    int itmp = 0;
    int i = 0;

    /* convert hex string to original */
    while (hex[i])
    {
        sscanf (&hex[i], "%02x", &itmp);
        sprintf (p, "%c", itmp);
        p++;
        i+=2;
    }
    *p = 0;

    printf ("\n hex2str: '%s'\n\n", hex2str);

    return 0;
}

Output

$ ./bin/c2h2c

 hex2str: 'hello'
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • I was stuck for hours on this, thank you! I didn't realized that i had the string representation and not the values, so my efforts to solve this problem were in the wrong directions. Let me thank you again for the explanation. – 1234stella1234 May 13 '15 at 23:06
  • Glad to help. I've added an update and got rid of the `strncpy`. – David C. Rankin May 13 '15 at 23:41