Ruby Bit Shift

I am currently converting a Visual Basic application to Ruby because we are moving it to the Internet. However, when converting some algorithms, I ran into the problem of bit shifting.

As I understand it, the problem is VB size masks applied to Integer types (as explained here ). Ruby does not distinguish between these types in practice.

So the problem is:

Visual basic

Dim i As Integer = 182
WriteLine(i << 24) '-1241513984

ruby

puts 182 << 24 # 3053453312

I work at Google and look at the beat, rearranging the last hours, but have not found a way or direction even to solve this problem.

+5
source share
1 answer

You need to reproduce what the visual base does, namely

  • mask the offset value as documented
  • 0xFFFFFFFF ( ruby ​​ bignum
  • , 2 ^ 32 ( 2s

def shift_32 x, shift_amount
  shift_amount &= 0x1F
  x <<= shift_amount
  x &= 0xFFFFFFFF 

  if (x & (1<<31)).zero?
   x
  else
   x - 2**32
  end
end
+7

All Articles