Bitwise operations: Difference between revisions
Content added Content deleted
m (→{{header|R}}) |
|||
Line 5,164: | Line 5,164: | ||
=== Native functions in R 3.x === |
=== Native functions in R 3.x === |
||
<lang |
<lang rsplus># Since R 3.0.0, the base package provides bitwise operators, see ?bitwAnd |
||
a <- 35 |
a <- 35 |
||
Line 5,178: | Line 5,178: | ||
===Using ''as.hexmode'' or ''as.octmode''=== |
===Using ''as.hexmode'' or ''as.octmode''=== |
||
<lang |
<lang rsplus>a <- as.hexmode(35) |
||
b <- as.hexmode(42) |
b <- as.hexmode(42) |
||
as.integer(a & b) # 34 |
as.integer(a & b) # 34 |
||
Line 5,186: | Line 5,186: | ||
===Using ''intToBits''=== |
===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. |
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 |
<lang rsplus>intToLogicalBits <- function(intx) as.logical(intToBits(intx)) |
||
logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb])) |
logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb])) |
||
"%AND%" <- function(x, y) |
"%AND%" <- function(x, y) |
||
Line 5,201: | Line 5,201: | ||
===Using ''bitops'' package=== |
===Using ''bitops'' package=== |
||
<lang |
<lang rsplus>library(bitops) |
||
bitAnd(35, 42) # 34 |
bitAnd(35, 42) # 34 |
||
bitOr(35, 42) # 43 |
bitOr(35, 42) # 43 |