Debian Codegraph @

awklib/eg/lib/strtonum.awk

raw
1 # mystrtonum --- convert string to number
2
3 #
4 # Arnold Robbins, [email protected], Public Domain
5 # February, 2004
6 # Revised June, 2014
7
8 function mystrtonum(str, ret, n, i, k, c)
9 {
10 if (str ~ /^0[0-7]*$/) {
11 # octal
12 n = length(str)
13 ret = 0
14 for (i = 1; i <= n; i++) {
15 c = substr(str, i, 1)
16 # index() returns 0 if c not in string,
17 # includes c == "0"
18 k = index("1234567", c)
19
20 ret = ret * 8 + k
21 }
22 } else if (str ~ /^0[xX][[:xdigit:]]+$/) {
23 # hexadecimal
24 str = substr(str, 3) # lop off leading 0x
25 n = length(str)
26 ret = 0
27 for (i = 1; i <= n; i++) {
28 c = substr(str, i, 1)
29 c = tolower(c)
30 # index() returns 0 if c not in string,
31 # includes c == "0"
32 k = index("123456789abcdef", c)
33
34 ret = ret * 16 + k
35 }
36 } else if (str ~ \
37 /^[-+]?([0-9]+([.][0-9]*([Ee][0-9]+)?)?|([.][0-9]+([Ee][-+]?[0-9]+)?))$/) {
38 # decimal number, possibly floating point
39 ret = str + 0
40 } else
41 ret = "NOT-A-NUMBER"
42
43 return ret
44 }
45
46 # BEGIN { # gawk test harness
47 # a[1] = "25"
48 # a[2] = ".31"
49 # a[3] = "0123"
50 # a[4] = "0xdeadBEEF"
51 # a[5] = "123.45"
52 # a[6] = "1.e3"
53 # a[7] = "1.32"
54 # a[8] = "1.32E2"
55 #
56 # for (i = 1; i in a; i++)
57 # print a[i], strtonum(a[i]), mystrtonum(a[i])
58 # }