Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate Bits Right operation in Ruby

Is there a Rotate Bits Right in Ruby ?

Or how can I do that please.

Thanks

like image 405
RobertPatt Avatar asked Aug 13 '10 12:08

RobertPatt


People also ask

How do you rotate a bit right?

Right rotation of bits in C programming is supported using bitwise right shift operator >> . Similar to left shift, right shift operations also results in bit loss. On every shift operation the least significant bit is dropped.

What is bitwise operator in Ruby?

Bitwise operator works on bits and performs bit by bit operation. The following Bitwise operators are supported by Ruby language. Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in either operand.


2 Answers

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
like image 168
Josh Lee Avatar answered Oct 11 '22 06:10

Josh Lee


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.

like image 36
Alex D Avatar answered Oct 11 '22 04:10

Alex D