2

I cannot believe there is no API to do this in GLib, for now I have only found people doing their own conversion, like here and here (function named "decode"). I would really like to find a way to do this in a simple GLib call, but if there is no way, the above methods don't work for me because the former is C++ (I'm using C/GObject) and the latter doesn't seem to work perfectly (I'm having problems with the length of the result).

TIA

Community
  • 1
  • 1
knocte
  • 16,941
  • 11
  • 79
  • 125
  • 1
    Could you clarify "doesn't seem to work perfectly (I'm having problems with the length of the result)"? – glglgl Aug 14 '11 at 23:17
  • 1
    You work from the assumption that this is a common task. It is not, users of your program are not typically skilled or able to enter hex strings. Binary to hex is a bit more common, your debugger knows how to do that. Step away from the machine for a bit. – Hans Passant Aug 15 '11 at 00:22

2 Answers2

0

As mentioned, this is a bit uncommon. If you have a short enough hex string, you can prefix it with 0x and use strtoll(). But for arbitrary length strings, here is a C function:

char *hex_to_string(const char *input)
{
    char a;
    size_t i, len;
    char *retval = NULL;
    if (!input) return NULL;

    if((len = strlen(input)) & 1) return NULL;

    retval = (char*) malloc(len >> 1);
    for ( i = 0; i < len; i ++)
    {
        a = toupper(input[i]);
        if (!isxdigit(a)) break;
        if (isdigit(a)) a -= '0';
        else a = a - 'A' + '\10';

        if (i & 1) retval[i >> 1] |= a;
        else retval[i >> 1] = a<<4;
    }
    if (i < len)
    {
        free(retval);
        retval = NULL;
    }

    return retval;
}
Seth
  • 2,683
  • 18
  • 18
0

I'm no 100% sure what you mean by "hexadecimal string" but may be this thread will be of some help.

Community
  • 1
  • 1
dtoux
  • 1,754
  • 3
  • 21
  • 38