2

Ruby Fixnums are 64-bit on 64-bit rubies:

bits = 8 * 0.size 
# => 64

The maximum signed integer under two's complement is 9_223_372_036_854_775_807, but the maximum Fixnum in Ruby is only half that:

[(1 << 62) - 1,  1 << 62].map(&:class)
# => [Fixnum, Bignum]
max = (1 << 62) - 1 
# => 4611686018427387903
max.to_s 2
# => "11111111111111111111111111111111111111111111111111111111111111" (62 bits)

How does Ruby use the missing bit? MRI Fixnum doc only mentions it briefly:

[Fixnum] Holds Integer values that can be represented in a native machine word (minus 1 bit). If any operation on a Fixnum exceeds this range, the value is automatically converted to a Bignum.

Tested with: MRI 2.1.2, JRuby 1.7.13, and Rubinius 2.2.10.

glebm
  • 20,282
  • 8
  • 51
  • 67
  • 2
    Not a duplicate, but your question is answered here: http://stackoverflow.com/questions/535721/ruby-max-integer Short version is that one bit is used to mark it as an int. – Some Guy Jul 06 '14 at 18:59
  • Thanks, found it: `one bit is used to mark it as an integer instead of an object reference`. More detail would be interesting. – glebm Jul 06 '14 at 19:16
  • Have you read the C source to see how `Fixnum`s work at the lower levels? The `fix_*` functions in `numeric.c` might be enlightening. – mu is too short Jul 06 '14 at 19:40
  • 1
    The chapter on extending Ruby in the Pickaxe book (which is available online) explains this quite well. See section 2.2, _Ruby Objects in C_ :http://media.pragprog.com/titles/ruby3/ext_ruby.pdf – matt Jul 06 '14 at 20:56
  • @matt Section 2.2 answers the question perfectly. If you answer with a quote from there I will accept. Many thanks. – glebm Jul 07 '14 at 15:15
  • Your code will output `[Integer, Integer]` as of Ruby 2.4.0. – David Grayson Jan 12 '17 at 03:22

0 Answers0