GLib API to convert hexadecimal string to ASCII string?
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 her开发者_开发百科e (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
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;
}
I'm no 100% sure what you mean by "hexadecimal string" but may be this thread will be of some help.
精彩评论