I am reading binary files in R and need to read 10 bytes, which must be interpreted as 4 bit unsigned integers (2 per byte, so 20 values in range 0..15 I guess).
From my understanding of the docs, this cannot done with readBin
directly because the minimal length to read, 1, means 1 byte.
So I think I need to read the data as 1 byte integers and use bit-wise operations to get the 4 bit integers. I found out that the values are stored as 32 bit integers internally by R, and I found this explanation on SO that seems to describe what I want to do. So here is my attempt at an R function that follows the advice:
#' @title Interprete bits start_index to stop_index of input int8 as unsigned integer.
uint8bits <- function(int8, start_index, stop_index) {
num_bits = stop_index - start_index + 1L;
bitmask = bitwShiftL((bitwShiftL(1L, num_bits) -1L), stop_index);
return(bitwShiftR(bitwAnd(int8, bitmask), start_index));
}
However, it does not work as intended, e.g, to get the two numbers out of the read value (255 in this example), I would call the function once to extract bits 1 to 4, and once more for bits 5 to 8:
value1 = uint8bits(255L, 1, 4); # I would expect 15, but the output is 120.
value2 = uint8bits(255L, 5, 8); # I would expect 15, but the output is 0.
What am I doing wrong?