Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I emulate integer overflow on a Fixnum variable?

I'm currently converting an algorithm from Java to Ruby, and I've hit a bit of a snag with the lack of integer overflowing in Ruby.

Say I have a value of 2663860877, this is bigger than the max integer 2147483648.

In Java, it wraps around and I should get -1631106419.

I found this bit of code, but it doesn't seem to be working:

def force_overflow(i)
  if i < -2147483648
    -(-(i) & 0xffffffff)
  elsif i > 2147483647
    i & 0xffffffff
  else
    i
  end
end

And'ing the variable doesn't force it negative like you'd expect.

like image 374
Jeff Adams Avatar asked Sep 09 '11 18:09

Jeff Adams


1 Answers

Assuming 32bit integers with two's complement negatives this should work:

def force_overflow_signed(i)
  force_overflow_unsigned(i + 2**31) - 2**31
end

def force_overflow_unsigned(i)
  i % 2**32   # or equivalently: i & 0xffffffff
end
like image 83
undur_gongor Avatar answered Oct 15 '22 21:10

undur_gongor