5

Is there a Rotate Bits Right in Ruby ?

Or how can I do that please.

Thanks

5
  • 1
    You'll have to give more details than that. Commented Aug 13, 2010 at 12:56
  • a function that mades : ror(0x08048586,1) => 0x86080485 Commented Aug 13, 2010 at 12:58
  • I have to say that that's still incredibly unclear - instead of assuming everyone knows what you're trying to achieve, give a little context and explain how/what/why and what you've tried to do so far. Commented Aug 13, 2010 at 13:01
  • Oh ... ROR = Rotate Right and not Ruby on Rails. If you change "ROR" to "Rotate Bits Right" then you'll get a better response ;) Commented Aug 13, 2010 at 13:01
  • That makes far more sense - I was reading it as Ruby on Rails Commented Aug 13, 2010 at 13:25

3 Answers 3

15

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
Sign up to request clarification or add additional context in comments.

2 Comments

0xFFFFFFFF can be replaced with ('1'*32).to_i(2) for 32 bits, so it's no longer hard-coded.
('1'*32).to_i(2) is not a good idea. It does cast, a slow operation. Better to use something like 2**32-1
1

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.

3 Comments

This gem does not install on windows (or from the issue on Mac). While it looks like it has a nice interface, it's not usable for me at the moment
@LukeChadwick Let me have a look and see if I can fix it on Windows.
@LukeChadwick, I have just released a new version which works on OS X. Could you check whether it can be installed on Windows now?
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.