hex format 2005-04-07 - By Peter Wolf
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
> >
______________________________________________ R-help@(protected) mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
|
|