Debian Codegraph @

src/common/qmi-common.c

raw
1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 /*
4 * Copyright (C) 2023 Fabio Porcedda <[email protected]>
5 */
6
7 #include "qmi-common.h"
8
9 #include <stdio.h>
10
11 /*****************************************************************************/
12
13 gchar *
14 qmi_common_str_hex (gconstpointer mem,
15 gsize size,
16 gchar delimiter)
17 {
18 const guint8 *data = mem;
19 gsize i;
20 gsize j;
21 gsize new_str_length;
22 gchar *new_str;
23
24 /* Get new string length. If input string has N bytes, we need:
25 * - 1 byte for last NUL char
26 * - 2N bytes for hexadecimal char representation of each byte...
27 * - N-1 bytes for the separator ':'
28 * So... a total of (1+2N+N-1) = 3N bytes are needed... */
29 new_str_length = 3 * size;
30
31 /* Allocate memory for new array and initialize contents to NUL */
32 new_str = g_malloc0 (new_str_length);
33
34 /* Print hexadecimal representation of each byte... */
35 for (i = 0, j = 0; i < size; i++, j += 3) {
36 /* Print character in output string... */
37 snprintf (&new_str[j], 3, "%02X", data[i]);
38 /* And if needed, add separator */
39 if (i != (size - 1) )
40 new_str[j + 2] = delimiter;
41 }
42
43 /* Set output string */
44 return new_str;
45 }