Bitwise operations: Difference between revisions

m
Line 5,164:
 
=== Native functions in R 3.x ===
<lang rrsplus># Since R 3.0.0, the base package provides bitwise operators, see ?bitwAnd
 
a <- 35
Line 5,178:
 
===Using ''as.hexmode'' or ''as.octmode''===
<lang rrsplus>a <- as.hexmode(35)
b <- as.hexmode(42)
as.integer(a & b) # 34
Line 5,186:
===Using ''intToBits''===
The logical operators in R, namely &, | and !, are designed to work on logical vectors rather than bits. It is possible to convert from integer to logical vector and back to make these work as required, e.g.
<lang Rrsplus>intToLogicalBits <- function(intx) as.logical(intToBits(intx))
logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb]))
"%AND%" <- function(x, y)
Line 5,201:
 
===Using ''bitops'' package===
<lang Rrsplus>library(bitops)
bitAnd(35, 42) # 34
bitOr(35, 42) # 43
1,336

edits