[R] Hexidecimal conversion

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Thu Dec 2 14:07:23 CET 2004


Some years ago I wrote a function to convert a number
from number system "base.in" to number system "base.out".
Here is the code:
<<*>>=
chcode <- function(b, base.in=2, base.out=10, digits="0123456789ABCDEF"){
   # change of number systems, pw 10/02
   # e.g.: from 2 2 2 2 ...  ->  16 16 16 ...
   digits<-substring(digits,1:nchar(digits),1:nchar(digits))
   if(length(base.in)==1) base.in <- rep(base.in, max(nchar(b)-1))
   if(is.numeric(b)) b <- as.character(as.integer(b))
   b.num <- lapply(strsplit(b,""), function(x) match(x,digits)-1  )
   result <- lapply(b.num, function(x){
                cumprod(rev(c(base.in,1))[ 1:length(x) ] ) %*% rev(x)
             } )
   number<-unlist(result)
   cat("decimal representation:",number,"\n")

   if(length(base.out)==1){
      base.out<-rep(base.out,1+ceiling(log( max(number), base=base.out ) ) )
   }
   n.base <- length(base.out); result <- NULL
   for(i in n.base:1){
     result <- rbind(number %% base.out[i], result)
     number <- floor(number/base.out[i])
   }
   result[]<-digits[result+1]
   apply(result, 2, paste, collapse="")
}


@
... a short check:
<<*>>=
chcode("9F",16,10)

@
output-start
decimal representation: 159
[1] "0159"
output-end
@
... conversion backwards:
<<*>>=
chcode("159",10,16)

@
output-start
decimal representation: 159
[1] "09F"
output-end

Is chcode the function you are looking for?

Peter Wolf


Hanke, Alex 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?
>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)
>              }
>Alex Hanke
>Department of Fisheries and Oceans
>St. Andrews Biological Station
>531 Brandy Cove Road
>St. Andrews, NB
>Canada
>E5B 2L9
>
>
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>  
>




More information about the R-help mailing list