Ruby最大整数 [英] Ruby max integer
问题描述
我需要能够确定Ruby中系统的最大整数.有人知道如何,或者是否有可能?
I need to be able to determine a systems maximum integer in Ruby. Anybody know how, or if it's possible?
推荐答案
Ruby在溢出时会自动将整数转换为大整数类,因此(实际上)对它们的大小没有限制.
Ruby automatically converts integers to a large integer class when they overflow, so there's (practically) no limit to how big they can be.
如果您正在寻找计算机的大小,即64位或32位,我发现此ruby-forum.com上的把戏:
If you are looking for the machine's size, i.e. 64- or 32-bit, I found this trick at ruby-forum.com:
machine_bytes = ['foo'].pack('p').size
machine_bits = machine_bytes * 8
machine_max_signed = 2**(machine_bits-1) - 1
machine_max_unsigned = 2**machine_bits - 1
如果要查找Fixnum对象的大小(小到足以存储在单个机器字中的整数),则可以调用0.size
以获取字节数.我猜它在32位版本上应该是4,但是我现在无法测试.同样,最大的Fixnum显然是2**30 - 1
(或2**62 - 1
),因为使用一位将其标记为整数而不是对象引用.
If you are looking for the size of Fixnum objects (integers small enough to store in a single machine word), you can call 0.size
to get the number of bytes. I would guess it should be 4 on 32-bit builds, but I can't test that right now. Also, the largest Fixnum is apparently 2**30 - 1
(or 2**62 - 1
), because one bit is used to mark it as an integer instead of an object reference.
这篇关于Ruby最大整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!