Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alexbevi
GitHub Repository: alexbevi/BizHawk
Path: blob/master/libsnes/bsnes/nall/atoi.hpp
2 views
1
#ifndef NALL_ATOI_HPP
2
#define NALL_ATOI_HPP
3
4
namespace nall {
5
6
//note: this header is intended to form the base for user-defined literals;
7
//once they are supported by GCC. eg:
8
//unsigned operator "" b(const char *s) { return binary(s); }
9
//-> signed data = 1001b;
10
//(0b1001 is nicer, but is not part of the C++ standard)
11
12
constexpr inline uintmax_t binary_(const char *s, uintmax_t sum = 0) {
13
return (
14
*s == '0' || *s == '1' ? binary_(s + 1, (sum << 1) | *s - '0') :
15
sum
16
);
17
}
18
19
constexpr inline uintmax_t octal_(const char *s, uintmax_t sum = 0) {
20
return (
21
*s >= '0' && *s <= '7' ? octal_(s + 1, (sum << 3) | *s - '0') :
22
sum
23
);
24
}
25
26
constexpr inline uintmax_t decimal_(const char *s, uintmax_t sum = 0) {
27
return (
28
*s >= '0' && *s <= '9' ? decimal_(s + 1, (sum * 10) + *s - '0') :
29
sum
30
);
31
}
32
33
constexpr inline uintmax_t hex_(const char *s, uintmax_t sum = 0) {
34
return (
35
*s >= 'A' && *s <= 'F' ? hex_(s + 1, (sum << 4) | *s - 'A' + 10) :
36
*s >= 'a' && *s <= 'f' ? hex_(s + 1, (sum << 4) | *s - 'a' + 10) :
37
*s >= '0' && *s <= '9' ? hex_(s + 1, (sum << 4) | *s - '0') :
38
sum
39
);
40
}
41
42
//
43
44
constexpr inline uintmax_t binary(const char *s) {
45
return (
46
*s == '0' && *(s + 1) == 'B' ? binary_(s + 2) :
47
*s == '0' && *(s + 1) == 'b' ? binary_(s + 2) :
48
*s == '%' ? binary_(s + 1) :
49
binary_(s)
50
);
51
}
52
53
constexpr inline uintmax_t octal(const char *s) {
54
return (
55
octal_(s)
56
);
57
}
58
59
constexpr inline intmax_t integer(const char *s) {
60
return (
61
*s == '+' ? +decimal_(s + 1) :
62
*s == '-' ? -decimal_(s + 1) :
63
decimal_(s)
64
);
65
}
66
67
constexpr inline uintmax_t decimal(const char *s) {
68
return (
69
decimal_(s)
70
);
71
}
72
73
constexpr inline uintmax_t hex(const char *s) {
74
return (
75
*s == '0' && *(s + 1) == 'X' ? hex_(s + 2) :
76
*s == '0' && *(s + 1) == 'x' ? hex_(s + 2) :
77
*s == '$' ? hex_(s + 1) :
78
hex_(s)
79
);
80
}
81
82
constexpr inline intmax_t numeral(const char *s) {
83
return (
84
*s == '0' && *(s + 1) == 'X' ? hex_(s + 2) :
85
*s == '0' && *(s + 1) == 'x' ? hex_(s + 2) :
86
*s == '0' && *(s + 1) == 'B' ? binary_(s + 2) :
87
*s == '0' && *(s + 1) == 'b' ? binary_(s + 2) :
88
*s == '0' ? octal_(s + 1) :
89
*s == '+' ? +decimal_(s + 1) :
90
*s == '-' ? -decimal_(s + 1) :
91
decimal_(s)
92
);
93
}
94
95
inline double fp(const char *s) {
96
return atof(s);
97
}
98
99
}
100
101
#endif
102
103