source: Daodan/MinGW/msys/1.0/share/awk/strtonum.awk@ 1158

Last change on this file since 1158 was 1046, checked in by alloc, 8 years ago

Daodan: Added Windows MinGW and build batch file

File size: 1.4 KB
RevLine 
[1046]1# strtonum --- convert string to number
2
3#
4# Arnold Robbins, arnold@skeeve.com, Public Domain
5# February, 2004
6
7function mystrtonum(str, ret, chars, n, i, k, c)
8{
9 if (str ~ /^0[0-7]*$/) {
10 # octal
11 n = length(str)
12 ret = 0
13 for (i = 1; i <= n; i++) {
14 c = substr(str, i, 1)
15 if ((k = index("01234567", c)) > 0)
16 k-- # adjust for 1-basing in awk
17
18 ret = ret * 8 + k
19 }
20 } else if (str ~ /^0[xX][0-9a-fA-f]+/) {
21 # hexadecimal
22 str = substr(str, 3) # lop off leading 0x
23 n = length(str)
24 ret = 0
25 for (i = 1; i <= n; i++) {
26 c = substr(str, i, 1)
27 c = tolower(c)
28 if ((k = index("0123456789", c)) > 0)
29 k-- # adjust for 1-basing in awk
30 else if ((k = index("abcdef", c)) > 0)
31 k += 9
32
33 ret = ret * 16 + k
34 }
35 } else if (str ~ /^[-+]?([0-9]+([.][0-9]*([Ee][0-9]+)?)?|([.][0-9]+([Ee][-+]?[0-9]+)?))$/) {
36 # decimal number, possibly floating point
37 ret = str + 0
38 } else
39 ret = "NOT-A-NUMBER"
40
41 return ret
42}
43
44# BEGIN { # gawk test harness
45# a[1] = "25"
46# a[2] = ".31"
47# a[3] = "0123"
48# a[4] = "0xdeadBEEF"
49# a[5] = "123.45"
50# a[6] = "1.e3"
51# a[7] = "1.32"
52# a[7] = "1.32E2"
53#
54# for (i = 1; i in a; i++)
55# print a[i], strtonum(a[i]), mystrtonum(a[i])
56# }
Note: See TracBrowser for help on using the repository browser.