Plan 9 from Bell Labs’s /usr/web/sources/contrib/quanstro/runetype-x/mystrtonum

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


function hex(s,        base, r, n, i, k, c)
{
	base = 16;
	if(s ~ /^0[xX][0-9a-fA-f]+/)
		s = substr(str, 3);
	n = length(s)
  	r = 0
	for (i = 1; i <= n; i++) {
		c = tolower(substr(s, i, 1))
		k = index("0123456789abcdef", c) - 1;
		r = r * base + k
	}
     	return r
}

function mystrtonum(str0,        neg, base, str, r, n, i, k, c)
{
	base = 0;
	neg = 0;
	str = str0;
	if(str ~ /^\+/)
		str = substr(str, 2)
	if(str ~ /^-/){
		str = substr(str, 2)
		neg = 1
	}
	if(str ~ /^0[0-7]*$/)
		base = 8
	if(str ~ /^0[xX][0-9a-fA-f]+/){
		str = substr(str, 3);
		base = 16;
	}
	if(base != 0){
		n = length(str)
  		r = 0
		for (i = 1; i <= n; i++) {
			c = tolower(substr(str, i, 1))
			k = index("0123456789abcdef", c) - 1;
			r = r * base + k
		}
	}else if(str ~ /^[0-9]*([.][0-9]*)?([Ee][-+]?[0-9]+)?$/)
		r = str0 + 0
	else
		r = "NaN"
     	return r
}

BEGIN{
	a[1] = "25"
	a[2] = ".31"
	a[3] = "0123"
	a[4] = "0xdeadBEEF"
	a[5] = "123.45"
	a[6] = "1.e3"
	a[7] = "1.32"
	a[7] = "1.32E2"
	
	for (i = 1; i in a; i++)
		print a[i], strtonum(a[i]), mystrtonum(a[i])
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].