Gavin Kistner
3/2/2007 2:43:00 PM
On Mar 2, 7:05 am, Jimmy Kofler <kofler...@mailinator.com> wrote:
> Can we translate the following C-coded prime sieve by Frank Pilhofer
> into a Ruby version that also uses bitwise operations?
Yes! Ruby supports bitwise operations on Integers. One thing to watch
out for: Ruby's integers are unbounded in size, so shifting left may
produce different results in a Ruby Integer than on a 32- or 64-bit
int in C. You'll need to mask the values whenever something might
overflow.
For example:
irb(main):001:0> i = 0x7FFF_FFFF
=> 2147483647
irb(main):002:0> '%032b' % i
=> "01111111111111111111111111111111"
irb(main):003:0> i2 = i << 1
=> 4294967294
irb(main):004:0> '%032b' % i2
=> "11111111111111111111111111111110"
irb(main):005:0> i4 = i << 2
=> 8589934588
irb(main):006:0> '%032b' % i4
=> "111111111111111111111111111111100"
irb(main):007:0> i4 = (i << 2) && 0xFFFF_FFFF
=> 4294967295
irb(main):008:0> '%032b' % i4
=> "11111111111111111111111111111111"