4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Integerに統合された整数をFixnumなのかBignumなのか判別する

4
Posted at

Ruby2.4以降、整数型が統合されましたが内部のデータ構造として
どちらを使っているのかが気になることがあります。

判別方法

class Integer
  def is_fixnum?
    __id__ == self * 2 + 1
  end
end

def is_fix(num)
  kls = num.is_fixnum? ? "Fixnum" : "Bignum"
  puts "#{num} is #{kls}"
end

is_fix(2**30-1)
is_fix(2**30)
is_fix(2**62-1)
is_fix(2**62)

何やってるの?

object_idを比べています。
Fixnumのobject_idは固定(かつ内部データの都合で数値*2+1)になります。

実はwindows-x64の場合Fixnumは64bit対応していない

windowsの場合の結果は

1073741823 is Fixnum
1073741824 is Bignum
4611686018427387903 is Bignum
4611686018427387904 is Bignum

Linuxの場合は

1073741823 is Fixnum
1073741824 is Fixnum
4611686018427387903 is Fixnum
4611686018427387904 is Bignum

となり、windowsの場合x64ビルドだろうがFixnumは30bit程度になります。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?