strtonum.awk 1.4 KB

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