-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnum.c
69 lines (54 loc) · 1.26 KB
/
num.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
#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include "num.h"
unsigned int ndigits(ull val) {
unsigned int len = 0;
do {
val /= 10;
len++;
} while (val);
return (len);
}
void ulltoa(char *str, ull val, const uint len) {
assert(str != NULL);
assert(len > 0);
double res = pow(10, len - 1);
assert(res > 0);
assert(res <= LLONG_MAX);
ull div = (ull) llround(res);
for (ull digit = 0; div > 0; div /= 10) {
digit = val / div;
*(str++) = (char) ('0' + digit);
val -= digit * div;
}
}
/* Modifed from OpenBSD to be rather minimal */
bool strtonum(const char *const numstr,
long long minval,
long long maxval,
long long *const res) {
assert(numstr != NULL);
assert(res != NULL);
long long ll = 0;
char *ep;
if (minval > maxval) {
errno = EINVAL;
return (false);
}
errno = 0;
ll = strtoll(numstr, &ep, 10);
if (numstr == ep || *ep != '\0')
errno = EINVAL;
else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
errno = ERANGE;
else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
errno = ERANGE;
if (errno != 0)
return (false);
*res = ll;
return (true);
}