Rotate Bits Right operation in Ruby

后端 未结 3 717
谎友^
谎友^ 2021-01-06 04:21

Is there a Rotate Bits Right in Ruby ?

Or how can I do that please.

Thanks

相关标签:
3条回答
  • 2021-01-06 04:41

    Some facts:

    • Ruby has operators << and >> to shift, but no built-in rotate operator. You have to fake it.
    • Ruby's Fixnum class automatically promotes to Bignum when the value exceeds the machine word size. This includes numbers that would fit in an unsigned word but not a signed word -- for example, 0xffffffff is a positive Bignum, not a negative Fixnum.

    So if you want a rotate operation, you a) have to write it using the shift operators, b) either hardcode 32 or 64 bits or ask Fixnum for the word size, and c) accept that the result might end up being a Bignum.

    That being said, this might work:

    class Integer
      def ror count
        (self >> count) | (self << (32 - count)) & 0xFFFFFFFF
      end
    end
    
    >> printf "0x%x\n", (0x01234567.ror 4)
    0x70123456
    
    0 讨论(0)
  • 2021-01-06 04:46

    ROR is rotate right.

    Here's a C implementation that could be ported to Ruby.

    Ruby does have the

    • << Bitwise Shift Left and
    • Bitwise Shift Right

    operators

    0 讨论(0)
  • 2021-01-06 04:47

    If you need higher performance, and don't mind adding a dependency, there is the bit-twiddle gem, which provides this operation implemented in native code:

    require 'bit-twiddle/core_ext'
    # rotate by 8 bits
    0x08048586.rrot32(8).to_s(16) # => "86080485"
    

    Disclosure: I'm the author of this gem.

    0 讨论(0)
提交回复
热议问题