libnm-util: consolidate hex-string <-> bin conversion functions

and move them to libnm-util's nm-utils.s so that they are easily available.
This commit is contained in:
Jiří Klimeš
2013-03-28 12:10:36 +01:00
parent bd3c80029d
commit 2109f41cc6
11 changed files with 129 additions and 310 deletions

View File

@@ -94,88 +94,6 @@ is_true (const char *str)
return FALSE;
}
static int
hex2num (char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
static int
hex2byte (const char *hex)
{
int a, b;
a = hex2num (*hex++);
if (a < 0)
return -1;
b = hex2num (*hex++);
if (b < 0)
return -1;
return (a << 4) | b;
}
/* free return value by caller */
gchar *
utils_hexstr2bin (const gchar * hex, size_t len)
{
size_t i;
int a;
const gchar *ipos = hex;
gchar *buf = NULL;
gchar *opos;
/* Length must be a multiple of 2 */
if ((len % 2) != 0)
return NULL;
opos = buf = g_malloc0 ((len / 2) + 1);
for (i = 0; i < len; i += 2) {
a = hex2byte (ipos);
if (a < 0) {
g_free (buf);
return NULL;
}
*opos++ = a;
ipos += 2;
}
return buf;
}
/* free return value by caller */
gchar *
utils_bin2hexstr (const gchar * bytes, int len, int final_len)
{
static gchar hex_digits[] = "0123456789abcdef";
gchar *result;
int i;
gsize buflen = (len * 2) + 1;
g_return_val_if_fail (bytes != NULL, NULL);
g_return_val_if_fail (len > 0, NULL);
g_return_val_if_fail (len < 4096, NULL); /* Arbitrary limit */
if (final_len > -1)
g_return_val_if_fail (final_len < buflen, NULL);
result = g_malloc0 (buflen);
for (i = 0; i < len; i++) {
result[2 * i] = hex_digits[(bytes[i] >> 4) & 0xf];
result[2 * i + 1] = hex_digits[bytes[i] & 0xf];
}
/* Cut converted key off at the correct length for this cipher type */
if (final_len > -1)
result[final_len] = '\0';
else
result[buflen - 1] = '\0';
return result;
}
GQuark
ifnet_plugin_error_quark (void)
{