J
jacob navia
What is the official behavior of ruby in case of integer overflow?
Thanks
Thanks
jacob said:What is the official behavior of ruby in case of integer overflow?
Integers overflow from Fixnums (30 bits) into Bignums (unlimited
precision integers).
irb(main):003:0> x = 2**30 - 1
=> 1073741823
irb(main):004:0> x.class
=> Fixnum
irb(main):005:0> x+1
=> 1073741824
irb(main):006:0> (x+1).class
=> Bignum
I haven't looked at it in several years, but at one time I was pretty
deep in that code and my recollection is that it's solid. Can you
explain your misgivings in more detail (e.g. outline a hypothetical
failure mode, even if you can't produce a concrete example)?
Fixnum seems to be a signed 63-bit integer (62 bits plus the sign bit) on my
64-bit system. I'm guessing that it's actually a 31-bit signed integer on a
32-bit system.
This is nice in that my programs don't really care, but will use a 64-bit
integer where it's efficient -- yet it strikes me that for smaller numbers, 32
bits would be more efficient, RAM-wise, if nothing else.
Integers overflow from Fixnums (30 bits) into Bignums (unlimited
precision integers).
system.irb(main):009:0> (2**62-1).class => Fixnum
irb(main):010:0> (2**62).class => Bignum
irb(main):012:0> ((-2)**62-1).class => Fixnum
irb(main):013:0> ((-2)**62).class => Bignum
Fixnum seems to be a signed 63-bit integer (62 bits plus the sign bit) on my 64-bit system.
I'm guessing that it's actually a 31-bit signed integer on a 32-bit
=3D> Fixnum =C2=A0-9223372036854775807JRuby 1.3.1 JIRB:
n =3D if RUBY_PLATFORM.downcase =3D=3D "java" then 63 else 30 end =C2=A0#= =3D> 63
nn =3D 2 ** n - 1 ; "#{nn.class} =C2=A0#{nn}" =C2=A0#=3D> Fixnum =C2=A0 9= 223372036854775807
nn =3D -nn =C2=A0 =C2=A0 =C2=A0 =C2=A0; "#{nn.class} =C2=A0#{nn}" =C2=A0#=
=3D> Fixnum =C2=A0-9223372036854775808nn =3D 2 ** n =C2=A0 =C2=A0 ; "#{nn.class} =C2=A0#{nn}" =C2=A0#=3D> Bignu= m =C2=A0 9223372036854775808
nn =3D -nn =C2=A0 =C2=A0 =C2=A0 =C2=A0; "#{nn.class} =C2=A0#{nn}" =C2=A0#=
=3D> Bignum =C2=A0-9223372036854775809nn =3D 2 ** n + 1 ; "#{nn.class} =C2=A0#{nn}" =C2=A0#=3D> Bignum =C2=A0 9= 223372036854775809
nn =3D -nn =C2=A0 =C2=A0 =C2=A0 =C2=A0; "#{nn.class} =C2=A0#{nn}" =C2=A0#=
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.