blob: 215588572c02d20e6f4e7f8cc545493e4d5e1450 [file] [log] [blame]
Harald Welted284cd92010-03-01 21:58:31 +01001
2#include <string.h>
3#include <stdint.h>
4#include <errno.h>
Harald Welteb59f9352010-03-25 11:37:04 +08005#include <stdio.h>
Harald Welted284cd92010-03-01 21:58:31 +01006
7#include <osmocore/utils.h>
8
Harald Welteb59f9352010-03-25 11:37:04 +08009static char namebuf[255];
Harald Welted284cd92010-03-01 21:58:31 +010010const char *get_value_string(const struct value_string *vs, uint32_t val)
11{
12 int i;
13
14 for (i = 0;; i++) {
15 if (vs[i].value == 0 && vs[i].str == NULL)
16 break;
17 if (vs[i].value == val)
18 return vs[i].str;
19 }
Harald Welteb59f9352010-03-25 11:37:04 +080020
21 snprintf(namebuf, sizeof(namebuf), "unknown 0x%x", val);
22 return namebuf;
Harald Welted284cd92010-03-01 21:58:31 +010023}
24
25int get_string_value(const struct value_string *vs, const char *str)
26{
27 int i;
28
29 for (i = 0;; i++) {
30 if (vs[i].value == 0 && vs[i].str == NULL)
31 break;
32 if (!strcasecmp(vs[i].str, str))
33 return vs[i].value;
34 }
35 return -EINVAL;
36}
Harald Weltea73e2f92010-03-04 10:50:32 +010037
38char bcd2char(uint8_t bcd)
39{
40 if (bcd < 0xa)
41 return '0' + bcd;
42 else
43 return 'A' + (bcd - 0xa);
44}
45
46/* only works for numbers in ascci */
47uint8_t char2bcd(char c)
48{
49 return c - 0x30;
50}
Harald Welte3eba9912010-07-30 10:37:29 +020051
52int hexparse(const char *str, uint8_t *b, int max_len)
53
54{
55 int i, l, v;
56
57 l = strlen(str);
58 if ((l&1) || ((l>>1) > max_len))
59 return -1;
60
61 memset(b, 0x00, max_len);
62
63 for (i=0; i<l; i++) {
64 char c = str[i];
65 if (c >= '0' && c <= '9')
66 v = c - '0';
67 else if (c >= 'a' && c <= 'f')
68 v = 10 + (c - 'a');
69 else if (c >= 'A' && c <= 'F')
70 v = 10 + (c - 'A');
71 else
72 return -1;
73 b[i>>1] |= v << (i&1 ? 0 : 4);
74 }
75
76 return i>>1;
77}
Harald Welte40481e82010-07-30 11:40:32 +020078
79static char hexd_buff[4096];
80
Harald Weltedee47cd2010-07-30 11:43:30 +020081static char *_hexdump(const unsigned char *buf, int len, char *delim)
Harald Welte40481e82010-07-30 11:40:32 +020082{
83 int i;
84 char *cur = hexd_buff;
85
86 hexd_buff[0] = 0;
87 for (i = 0; i < len; i++) {
88 int len_remain = sizeof(hexd_buff) - (cur - hexd_buff);
Harald Weltedee47cd2010-07-30 11:43:30 +020089 int rc = snprintf(cur, len_remain, "%02x%s", buf[i], delim);
Harald Welte40481e82010-07-30 11:40:32 +020090 if (rc <= 0)
91 break;
92 cur += rc;
93 }
94 hexd_buff[sizeof(hexd_buff)-1] = 0;
95 return hexd_buff;
96}
Harald Weltedee47cd2010-07-30 11:43:30 +020097
98char *hexdump(const unsigned char *buf, int len)
99{
100 return _hexdump(buf, len, " ");
101}
102
103char *hexdump_nospc(const unsigned char *buf, int len)
104{
105 return _hexdump(buf, len, "");
106}