[R] Hexidecimal conversion
Hanke, Alex
HankeA at mar.dfo-mpo.gc.ca
Thu Dec 2 15:28:32 CET 2004
Thanks to Patrick Burns, Peter Wolf and Duncan Murdoch who all provided me
with workable solutions to the hexidecimal conversion problem. They all work
and basically differ in the number of bells and whistles.
Alex
-----Original Message-----
From: Duncan Murdoch [mailto:murdoch at stats.uwo.ca]
Sent: December 2, 2004 9:42 AM
To: Hanke, Alex
Subject: Re: [R] Hexidecimal conversion
On Wed, 01 Dec 2004 15:07:16 -0400, "Hanke, Alex"
<HankeA at mar.dfo-mpo.gc.ca> wrote :
>
>Help
>I can produce the hexidecimal equivalent of a decimal number but I am
having
>a hard time reversing the operation. I'm good for hex representations to
159
>and am close to extending to 2559. The archives are not clear on the
>existence of a function for this task. Is there one?
I don't think so.
>Here is what I have got so far:
>#Good for hex values to "9F"
>as.decmode<-function(as.character(x)){
> hexDigit<-c(0:9,LETTERS[1:6])
> z<-matrix(c(strsplit(x, NULL),recursive=T),
> length(x),2,byrow=T)
> z.1<-as.numeric(z[,1])
> z.2<- match(z[,2],hexDigit)-1
> dec<-16*z.1+z.2
> return(dec)
> }
I think what you're missing is a loop over the characters. You can
probably vectorize this to make it more efficient, but here's a
sketch:
hex2numeric <- function(x) {
hexDigits <- c(0:9, LETTERS[1:6])
chars <- strsplit(toupper(x), split=NULL)
result <- rep(0, length(chars))
for (i in seq(along=chars)) {
for (j in seq(along=chars[[i]]))
result[i] <- 16*result[i] + match(chars[[i]][j],
hexDigits) - 1
}
result
}
Duncan Murdoch
More information about the R-help
mailing list