Bitwise operations: Difference between revisions

Added R code
No edit summary
(Added R code)
Line 779:
 
In this example we show a relatively straightforward function for converting integers into strings of bits, and another simple ''mask()'' function to create arbitrary lengths of bits against which we perform our masking operations. Also note that the implementation of these functions defaults to single bit rotations of 8-bit bytes. Additional arguments can be used to over-ride these defaults. Any case where the number of rotations modulo the width is zero represents a rotation of all bits back to their starting positions. This implementation should handle any integer number of rotations over bitfields of any valid (positive integer) length.
 
=={{header|R}}==
<lang R>
bitoperations <- function(intx, inty)
{
#NOTE: intToBits() is an alternative to rawToBits(as.raw()). In that case, all logical vectors will be 32 long, rather than 8.
int2logicalbits <- function(intx) as.logical(rawToBits(as.raw(intx)))
x <- int2logicalbits(intx)
y <- int2logicalbits(inty)
message("x: ")
print(x)
message("y: ")
print(y)
message("x and y: ")
print(x & y)
message("x or y: ")
print(x | y)
message("x xor y: ")
print(xor(x, y))
message("not x: ")
print(!x)
shift <- function(intx, amount) as.logical(rawToBits(rawShift(as.raw(intx), amount)))
message("'left' shift x one place") #NOTE2: directions are 'wrong' because the least significant digit is on the left
print(shift(intx, 1))
message("'right' shift x one place: ")
print(shift(intx, -1))
message("'left' shift x, y places")
print(shift(intx, y))
 
#NOTE3: There is probably a better way to do bit rotation than this
rotate <- function(x, amount)
{
direction <- ifelse(amount > 0, "left", "right")
if(direction=="left")
{
len <- length(x)
for(i in 1:amount)
{
x <- c(x[len], x[-len])
}
} else
{
for(i in 1:(-amount))
{
x <- c(x[-1], x[1])
}
}
x
}
message("x rotated 1 place 'left'")
print(rotate(x, 1))
message("x rotated 1 place 'right'")
print(rotate(x, -1))
message("x rotated y places 'left'")
print(rotate(x, inty))
message("x rotated y places 'right'")
print(rotate(x, -inty))
}
 
bitoperations(35, 42)
</lang>
 
 
=={{header|Ruby}}==