[R] unsigned 4 byte number

William Dunlap wdunlap at tibco.com
Tue May 18 19:22:48 CEST 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of tetonedge
> Sent: Tuesday, May 18, 2010 9:14 AM
> To: r-help at r-project.org
> Subject: [R] unsigned 4 byte number
> 
> 
> Does anybody know how to read in a unsigned 4 byte number 
> from a binary file?
> According to the help for readBin, the signed argument only applies to
> size=1 or 2. But if you declare any size larger it assumes it 
> is signed?

R cannot properly represent unsigned 4 byte C ints with its
type "integer" (which is a 4 byte signed C int).  It can store
them as doubles with the desired values.

You can use readBin to read them as signed 4 byte C ints, stored
in R "integers",  with

i <- readBin(file, what="integer", size=4)

and then convert them to doubles with the following function

unsignedFourByteIntToDouble <- function(i) {
   d <- as.numeric(i)
   d[d<0] <- d[d<0] + 2^32
   d
}

If you had S+ you could do this in one step using readBin's
output="double" argument.   In S+'s readBin(), output=type
means to override the default mapping of C types to S+ types.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> Thanks
> -- 
> View this message in context: 
> http://r.789695.n4.nabble.com/unsigned-4-byte-number-tp2221555
p2221555.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list