Bignum
objects hold integers outside the range of Fixnum
. Bignum
objects are created automatically when integer calculations would otherwise overflow a Fixnum
. When a calculation involving Bignum
objects returns a result that will fit in a Fixnum
, the result is automatically converted.
For the purposes of the bitwise operations and []
, a Bignum
is treated as if it were an infinite-length bitstring with 2's complement representation.
While Fixnum
values are immediate, Bignum
objects are not—assignment and parameter passing work with references to objects, not the objects themselves.
big | + |
aNumeric | Addition |
big | - |
aNumeric | Subtraction |
big | * |
aNumeric | Multiplication |
big | / |
aNumeric | Division |
big | % |
aNumeric | Modulo |
big | ** |
aNumeric | Exponentiation |
Bignum
.~ big |
Invert bits | ||
big | | |
aNumeric | Bitwise OR |
big | & |
aNumeric | Bitwise AND |
big | ^ |
aNumeric | Bitwise EXCLUSIVE OR |
big | << |
aNumeric | Left-shift aNumeric bits |
big | >> |
aNumeric | Right-shift aNumeric bits (with sign extension) |
Comparable
.
a = 9**15
50.downto(0) do |n|
print a[n]
end
produces:
000101110110100000111000011110010100111100010111001
(256**10 - 1).size → 12
(256**20 - 1).size → 20
(256**40 - 1).size → 40
Float
. If big doesn't fit in a
Float
, the result is infinity.
Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.