[R] Converting IEEE Float in 16 char hex back to float

Duncan Murdoch murdoch at stats.uwo.ca
Sat Feb 27 18:44:52 CET 2010


On 27/02/2010 12:43 AM, xlr82sas wrote:
> Hi,
> 
> If I do the following
> 
> sprintf("%A",pi)
> "0X1.921FB54442D18"
> 
> I have this 16 byte character string
> 
> hx<-"400921FB54442D18"
> 
> This is the exact hex16 representation of PI in
> IEEE float that R uses in Intel 32bit(little endian) Windows
> SAS uses the same representation. 11 bit exponent and 53 bit mantissa.
> 
> I want to do is recreate the float exactly from the 16 char hex
> 
> something like
> 
> MyPI<-readChar(hx,numeric(),16)
> 
> or in SAS
> 
> MyPI=input("400921FB54442D18",hex16.);
> put MyPI=;
> 
> MYPI=3.1415926536
> 
> What I am trying to do is set up a lossless
> transfer method from SAS to R

The way I would do it is to convert the hx string to raw bytes, then 
read the raw bytes as a binary value.  I think this works for one 
string; it would need some work to handle more than one:

hexdigits <- function(s) {
    digits <- 0:15
    names(digits) <- c(0:9, LETTERS[1:6])
    digits[strsplit(s, "")[[1]]]
}

bytes <- function(s) {
    digits <- matrix(hexdigits(s), ncol=2, byrow=TRUE)
    as.raw(digits %*% c(16,1))
}

todouble <- function(bytes) {
    con <- rawConnection(bytes)
    val <- readBin(con, "double", endian="big")
    close(con)
    val
}

todouble(bytes("400921FB54442D18"))



More information about the R-help mailing list