Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Ruby store large numbers? [duplicate]

Ruby can store extremely large numbers. Now that I think about it though, I don't even know how that's possible.

Computers store data in a series of two digits (0s and 1s). This is referred to as binary notation. However, there is a limit to the size of numbers they can store.

Most current Operating Systems these days run at 64 bits. That means the highest allocatable address space for a variable is 64 bits.

Integers are stored in a base 2 system, which means the highest value a computer should be able to store is

1111111111111111111111111111111111111111111111111111111111111111

Since computers can only read 2 possible values, this means the above number can be represented as

2 ^ 64

This means that the highest value an integer can read should be at most 18,446,744,073,709,551,615

I honestly don't even understand how it's possible to store integer values higher than that.

like image 663
Darkmouse Avatar asked Apr 20 '26 01:04

Darkmouse


1 Answers

Ruby uses Bignum objects to store number larger than 2^64. You can see here a description of how this works:

class_diagram

On the left, you can see RBignum contains an inner structure called RBasic, which contains internal, technical values used by all Ruby objects. Below that I show values specific to Bignum objects: digits and len. digits is a pointer to an array of 32-bit values that contain the actual big integer’s bits grouped into sets of 32. len records how many 32-bit groups are in the digits array. Since there can be any number of groups in the digits array, Ruby can represent arbitrarily large integers using RBignum.

like image 190
Uri Agassi Avatar answered Apr 22 '26 17:04

Uri Agassi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!