forked from gawen947/wsn-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atoi-gen.c
130 lines (103 loc) · 2.53 KB
/
atoi-gen.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/* File: atoi-gen.c
Copyright (C) 2013 David Hauweele <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
#include <err.h>
#include "atoi-gen.h"
static unsigned int symbol_value(char c)
{
/* digit */
if(c <= '9')
return c - '0';
/* lowercase */
if(c > 'Z')
return c - 'a' + 10;
/* uppercase */
return c - 'A' + 10;
}
int atoi_gen(const char *s)
{
int sgn = 1;
int val = 0;
unsigned int base = 10;
#define ZERO_END(c) if(c == '\0') goto RESULT
/* Skip leading spaces */
for(; isspace(*s) ; s++)
ZERO_END(*s);
ZERO_END(*s);
if(*s == '-') {
sgn = -1;
ZERO_END(*++s);
}
if(*s == '0') {
ZERO_END(*++s);
switch(*s) {
case 'x':
case 'X':
base = 16;
s++;
break;
case 'b':
case 'B':
base = 2;
s++;
break;
default:
base = 8;
}
}
/* Convert from base */
for(; !isspace(*s) ; s++) {
ZERO_END(*s);
val *= base;
val += symbol_value(*s);
}
for(; isspace(*s) ; s++)
ZERO_END(*s);
RESULT:
return val * sgn;
}
static bool ishex(char c)
{
if((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'F') ||
(c >= 'a' && c <= 'f'))
return true;
return false;
}
const char * parse_hex_until(const char *s, const char *delim,
unsigned int *v, const char *error_message,
bool accept_zero)
{
unsigned int val = 0;
const char *d;
if(!ishex(*s))
errx(EXIT_FAILURE,"%s: expect an hexadecimal value", error_message);
for(; *s != '\0' ; s++) {
d = strchr(delim, *s);
if(d)
goto EXIT;
if(!ishex(*s))
errx(EXIT_FAILURE, "%s: expect an hexadecimal value", error_message);
val <<= 4;
val += symbol_value(*s);
}
if(!accept_zero)
errx(EXIT_FAILURE, "%s: premature ending", error_message);
EXIT:
*v = val;
return s;
}