Skip to content

Chars as numbers

2 messages · Josef Eschgfaeller, Martin Maechler

#
Some weeks ago one discussed on the list about how
to transform a hexadecimal representation to
decimal digits. Specifically one has to transform
'a' to 10 etc. In C one does this with 'a'-87,
but I did not find a function for this in R.
Using match on letterdigits as in the following
is of course a little slow when repeated often.
---------------------------------------
Hex = function (rep16)
{rep16=tolower(rep16)
u=strsplit(rep16,'',perl=T)[[1]]
letterdigits=c(0:9,letters)
v=sapply(u,function (x)
   match(x,letterdigits)-1)
v=as.numeric(v)
Horner(v,16)}

Horner = function (v,alfa=2)
{b=v[1]; m=length(v)
if (m>1) for (i in 2:m)
b=b*alfa+v[i]; b}

# Example:
for (x in c('0','a0','10e','f0ae'))
print(Hex(x))
# 0
# 160
# 270
# 61614
---------------------------------------
Josef Eschgf??ller
2 days later
#
Package 'sfsmisc'
has a function  AsciiToInt() and a few useful related "R-code"
only functions such as chars8bit();  see the help pages once
you've installed and attached the package.

But do note that these things do depend on the encoding, as Uwe
Ligges has already told you.
Things work fine for pure  ASCII {independently of encoding}
but already differ for Umlauts / Accents
between iso-latin-1 or Unicode.

Martin Maechler, ETH Zurich