Search code examples
rr-rasterrgdal

apply function (Bitwise "and") on each cell of a raster in R?


What is the best way to do an "bitwise and" on all pixels in a raster (maybe using the "raster" package)? I want to check if the sixth bit is set.

If I was given an integer, I would use R's bitwAnd operator. I would 'and' with 32 (has only the sixth bit set) and see if the result is zero or otherwise. For example: bitwAnd(96,32) # 32, has sixth bit set bitwAnd(192,32) # 0, does not have the sixth bit set

I tried bitwAnd(myraster,32L) but it does not work.

Thanks! R.


Solution

  • For operations on each cell of a raster, you can use function calc of library raster. In your case, this would be:

    r.test <- calc(myraster, fun = function(x) bitwAnd(x,32L))