[R] hex format

Earl F. Glynn efg at stowers-institute.org
Thu Apr 7 16:52:04 CEST 2005


"Prof Brian Ripley" <ripley at stats.ox.ac.uk> wrote in message
news:Pine.LNX.4.61.0504071442200.25401 at gannet.stats...
> On Thu, 7 Apr 2005, Steve Vejcik wrote:
> > Has anyone used hex notation within R to represents integers?

>  Short answer: yes.
>
> > as.numeric("0x1AF0")
> [1] 6896
>
> (which BTW is system-dependent, but one person used it as you asked).

I see this works fine with R 2.0.0 on a Linux platform, but doesn't work at
all under R 2.0.1 on Windows.

> as.numeric("0x1AF0")
[1] NA
Warning message:
NAs introduced by coercion

Seems to me the conversion from hex to decimal should be system independent
(and makes working with colors much more convenient).  Why isn't this system
independent now?

The "prefix" on hex numbers is somewhat language dependent ("0x" or $)
perhaps but I didn't think this conversion should be system dependent.

I don't remember where I got this, but this hex2dec works under both Linux
and Windows (and doesn't need the "0x" prefix).

hex2dec <- function(hexadecimal)
{
  hexdigits <- c(0:9, LETTERS[1:6])
  hexadecimal <- toupper(hexadecimal)    # treat upper/lower case the same
  decimal <- rep(0, length(hexadecimal))
  for (i in 1:length(hexadecimal))
  {
    digits <- match(strsplit(hexadecimal[i],"")[[1]], hexdigits) - 1
    decimal[i] <- sum(digits * 16^((length(digits)-1):0))
  }
  return(decimal)
}

Example:
> hex2dec(c("1AF0", "FFFF"))
[1]  6896 65535

"FFFF" can be interpreted as 65535 as unsigned and -1 as signed on the same
system depending on context.  This isn't system dependent, but rather
context dependent.

I suggest "as.numeric" should perform the unsigned conversion on all
systems.  What am I missing?

efg
--
Earl F. Glynn
Scientific Programmer
Bioinformatics Department
Stowers Institute for Medical Research




More information about the R-help mailing list