Bit shifting in Ruby

前提是你 提交于 2019-12-05 08:05:17

You need to replicate what visual basic is doing, namely

  • mask the shift value as documented
  • cap mask the result with 0xFFFFFFFF (since ruby will have promoted the value to a bignum for you
  • if the top most bit is set, subtract 2^32 from the result (since signed integers are stored with 2s complement

For example

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!