Search code examples
rbit-manipulationbitwise-operatorsbit-shift32-bit

How to do bitwise shifting for signed (negative) integers?


In c-syntax, we can shift signed integers (negatives): We can use ">>>" if we want to force and unsigned integer shift.

y = -1732584194
(y>>16)

-26438

x = 1732584193
(x>>16)

26437

Using R, there are bitwise operators https://stat.ethz.ch/R-manual/R-devel/library/base/html/bitwise.html

?bitwShiftL for example shows the same page. It states: "Shifting is done assuming the values represent unsigned integers."

y = -1732584194
bitwShiftR(y,16)  
# [1] 39098     ## wanted -26438


x = 1732584193
bitwShiftR(x,16)
# [1] 26437    ## works as expected

Show how do I perform a signed shift using R statistical programming language?


Solution

  • You can define your own function to do this:

    Rshift <- function(val, nbits) floor(val/2^nbits)
    

    Which gives:

    y = -1732584194
    Rshift(y, 16)
    #> [1] -26438
    
    y = 1732584194
    Rshift(y, 16)
    #> [1] 26437
    

    Or if you are used to coding in C, write a function in C and compile it as an R function using Rcpp:

    Rcpp::cppFunction("long long RShift(long long a, int b) { return a >> b;}")
    
    y = -1732584194
    RShift(y, 16)
    #> [1] -26438
    
    y = 1732584194
    RShift(y, 16)
    #> [1] 26437