codekingpro/portable-devtools
114k
1# mystrtonum --- convert string to number2#3# This file and how to use it are described in the manual.4# Therefore, we respectfully advise you to Read The Fine Manual5# for more information.6#7# Arnold Robbins, arnold@skeeve.com, Public Domain8# February, 20049# Revised June, 201410 11function mystrtonum(str, ret, n, i, k, c)12{13 if (str ~ /^0[0-7]*$/) {14 # octal15 n = length(str)16 ret = 017 for (i = 1; i <= n; i++) {18 c = substr(str, i, 1)19 # index() returns 0 if c not in string,20 # includes c == "0"21 k = index("1234567", c)22 23 ret = ret * 8 + k24 }25 } else if (str ~ /^0[xX][[:xdigit:]]+$/) {26 # hexadecimal27 str = substr(str, 3) # lop off leading 0x28 n = length(str)29 ret = 030 for (i = 1; i <= n; i++) {31 c = substr(str, i, 1)32 c = tolower(c)33 # index() returns 0 if c not in string,34 # includes c == "0"35 k = index("123456789abcdef", c)36 37 ret = ret * 16 + k38 }39 } else if (str ~ \40 /^[-+]?([0-9]+([.][0-9]*([Ee][0-9]+)?)?|([.][0-9]+([Ee][-+]?[0-9]+)?))$/) {41 # decimal number, possibly floating point42 ret = str + 043 } else44 ret = "NOT-A-NUMBER"45 46 return ret47}48 49# BEGIN { # gawk test harness50# a[1] = "25"51# a[2] = ".31"52# a[3] = "0123"53# a[4] = "0xdeadBEEF"54# a[5] = "123.45"55# a[6] = "1.e3"56# a[7] = "1.32"57# a[8] = "1.32E2"58#59# for (i = 1; i in a; i++)60# print a[i], strtonum(a[i]), mystrtonum(a[i])61# }62 