[R] How to read a binary file bit by bit?

Duncan Murdoch murdoch at stats.uwo.ca
Fri May 29 12:35:00 CEST 2009


Inigo Pagola Barrio wrote:
> Hello everybody,
>
> I am trying to a read a binary file with different formats. I use the readBin function so I can read bytes, short and double numbers depending on the bytes per element in the byte stream. But now I need to read bit by bit, and join them in groups of ten because every ten bits will form a number. How can I do this?
>   
There are packages that perform bit operations, but I don't think you 
need that.  Since 5 bytes make 4 of your numbers, why not read the data 
as bytes, then convert in groups of 5?  E.g. if b is a vector of bytes, 
then the first of your numbers is something like b[1] + 256*(b[2] %% 
4).  The second would be b[2] %/% 4 + 64*(b[3] %% 16).  (These might not 
be the right formulas:  there are lots of ways to pack10 bit numbers 
into bytes.  You need to know which one was used in your file.)

Duncan Murdoch




More information about the R-help mailing list