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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With