Mercurial > hg > dmlib
comparison src/dmlib.c @ 2004:161e731eb152
Improve dmGetIntVal() to accept an optional negative value boolean flag
pointer. Also improve error handling in it.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Sat, 07 Jul 2018 01:11:22 +0300 |
parents | 12d4da502fa4 |
children | 3d40a6767a4e |
comparison
equal
deleted
inserted
replaced
2003:2ae47dcaaf10 | 2004:161e731eb152 |
---|---|
134 return ptr; | 134 return ptr; |
135 } | 135 } |
136 #endif | 136 #endif |
137 | 137 |
138 | 138 |
139 BOOL dmGetIntVal(const char *s, unsigned int *i) | 139 BOOL dmGetIntVal(const char *str, unsigned int *value, BOOL *neg) |
140 { | 140 { |
141 if (s[0] == '$') | 141 int ch; |
142 { | 142 BOOL hex = FALSE; |
143 if (sscanf(&s[1], "%x", i) < 1) | 143 |
144 // Is the value negative? | |
145 if (*str == '-') | |
146 { | |
147 if (neg == NULL) | |
144 return FALSE; | 148 return FALSE; |
145 } | 149 |
146 else if (s[0] == '0' && s[1] == 'x') | 150 *neg = TRUE; |
147 { | 151 str++; |
148 if (sscanf(&s[2], "%x", i) < 1) | |
149 return FALSE; | |
150 } | 152 } |
151 else | 153 else |
152 { | 154 if (neg != NULL) |
153 if (sscanf(s, "%u", i) < 1) | 155 *neg = FALSE; |
154 return FALSE; | 156 |
157 // Is it hexadecimal? | |
158 if (*str == '$') | |
159 { | |
160 hex = TRUE; | |
161 str++; | |
162 } | |
163 else | |
164 if (str[0] == '0' && str[1] == 'x') | |
165 { | |
166 hex = TRUE; | |
167 str += 2; | |
168 } | |
169 | |
170 // Parse the value | |
171 *value = 0; | |
172 if (hex) | |
173 { | |
174 while ((ch = *str++)) | |
175 { | |
176 if (ch >= '0' && ch <= '9') | |
177 { | |
178 *value <<= 4; | |
179 *value |= ch - '0'; | |
180 } | |
181 else | |
182 if (ch >= 'A' && ch <= 'F') | |
183 { | |
184 *value <<= 4; | |
185 *value |= ch - 'A'; | |
186 } | |
187 else | |
188 if (ch >= 'a' && ch <= 'f') | |
189 { | |
190 *value <<= 4; | |
191 *value |= ch - 'a'; | |
192 } | |
193 else | |
194 return FALSE; | |
195 } | |
196 } | |
197 else | |
198 { | |
199 while ((ch = *str++)) | |
200 { | |
201 if (ch >= '0' && ch <= '9') | |
202 { | |
203 *value *= 10; | |
204 *value += ch - '0'; | |
205 } | |
206 else | |
207 return FALSE; | |
208 } | |
155 } | 209 } |
156 return TRUE; | 210 return TRUE; |
157 } | 211 } |
158 | 212 |
159 | 213 |