[R] Converting numbers to and from raw
Stavros Macrakis
macrakis at alum.mit.edu
Fri May 15 21:22:02 CEST 2009
How can I convert an integer or double to and from their internal
representation as raws of length 4 and 8?
The following works for positive integers (including those represented
as floats):
# Convert integer (represented as integer or double) to sequence
# of raw bytes, least-significant byte first.
# intToRaw(0) => raw(0)
# intToRaw(17^9) => 91 64 63 9c 1b
# intToRaw(2^60/3) => 40 55 55 55 55 55 55 05 (note effect of finite precision)
intToRaw <- function(x, n=max(0,floor(log(x)/log(256)+1))) {
stopifnot(x>=0)
suppressWarnings(
as.raw( floor( x / 2^(8*seq(0,length=n)) ) %% 256))
}
but I'd think there was a simpler version that just casts the integer
as a bytestring internally (for type integer at least). Also, of
course, it doesn't help for getting the bit-pattern of a double.
-s
More information about the R-help
mailing list