[R] hex format

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Thu Apr 7 17:40:27 CEST 2005


Steve Vejcik wrote:

>Thanks for your advice.  Unfortunately, your answers are inconsistent:
>as.numeric("0x1AF0") returns a decimal value for a hex string. I'd like
>to do the opposite-use hex notation to represent a decimal.
>e.g.
>    x<-0x000A
>    y<-0x0001
>    x+y=0x00B
>     
>     Cheers.
>
you can use chcode() to define hex.to.dec(), dec.to.hex() and sum.hex()
to operate with hex numbers.

Peter Wolf

----------------------------------------------

<<define chcode>>=
chcode <- function(b, base.in=2, base.out=10, digits="0123456789ABCDEF"){
   # change of number systems, pwolf 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="")
}

@
<<define hex.to.dec, dec.to.hex and sum.hex>>=
hex.to.dec<-function(x) as.numeric(chcode(x, base.in=16, base.out=10))
dec.to.hex<-function(x) chcode(x, base.in=10, base.out=16)
sum.hex<-function(x,y) dec.to.hex(hex.to.dec(x) + hex.to.dec(y))

@
quick test:
<<define hex numbers>>=
a<-dec.to.hex(10); print(a)
b<-dec.to.hex(3);print(b)

@
output-start
decimal representation: 10
[1] "0A"
decimal representation: 3
[1] "03"
output-end

@
<<sum of a and b>>=
sum.hex(a,b)

@
output-start
decimal representation: 10
decimal representation: 3
decimal representation: 13
Thu Apr  7 17:31:42 2005
[1] "0D"
output-end

>  
>




More information about the R-help mailing list