4 * Copyright (C) 2008 Stefan Walter
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 2.1 of
9 * the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21 * Author: Stef Walter <stefw@thewalter.net>
30 static const char HEXC_UPPER[] = "0123456789ABCDEF";
31 static const char HEXC_LOWER[] = "0123456789abcdef";
34 egg_hex_decode (const gchar *data, gssize n_data, gsize *n_decoded)
36 return egg_hex_decode_full (data, n_data, 0, 1, n_decoded);
40 egg_hex_decode_full (const gchar *data,
54 g_return_val_if_fail (data || !n_data, NULL);
55 g_return_val_if_fail (n_decoded, NULL);
56 g_return_val_if_fail (group >= 1, NULL);
59 n_data = strlen (data);
60 n_delim = delim ? strlen (delim) : 0;
61 decoded = result = g_malloc0 ((n_data / 2) + 1);
64 while (n_data > 0 && state == 0) {
66 if (decoded != result && delim) {
67 if (n_data < n_delim || memcmp (data, delim, n_delim) != 0) {
76 while (part < group && n_data > 0) {
78 /* Find the position */
79 pos = strchr (HEXC_UPPER, g_ascii_toupper (*data));
88 *decoded = (j & 0xf) << 4;
91 *decoded |= (j & 0xf);
115 egg_hex_encode (gconstpointer data, gsize n_data)
117 return egg_hex_encode_full (data, n_data, TRUE, NULL, 0);
121 egg_hex_encode_full (gconstpointer data,
133 g_return_val_if_fail (data || !n_data, NULL);
136 hexc = upper_case ? HEXC_UPPER : HEXC_LOWER;
138 result = g_string_sized_new (n_data * 2 + 1);
143 if (delim && group && bytes && (bytes % group) == 0)
144 g_string_append (result, delim);
146 j = *(input) >> 4 & 0xf;
147 g_string_append_c (result, hexc[j]);
149 j = *(input++) & 0xf;
150 g_string_append_c (result, hexc[j]);
156 /* Make sure still null terminated */
157 return g_string_free (result, FALSE);