Forum: Ruby limiting Ruby Numbers

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Guest (Guest)
on 2006-06-10 13:16
is there any ways to limit ruby numbers up to certain bytes? all i've
read is that ruby numbers are limited to host's free memory
Simen E. (Guest)
on 2006-06-10 15:38
(Received via mailing list)
What exactly are you trying to do? From the Fixnum documentation:

"A 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.

Fixnum objects have immediate value. This means that when they are
assigned or passed as parameters, the actual object is passed, rather
than a reference to that object. Assignment does not alias Fixnum
objects. There is effectively only one Fixnum object instance for any
given integer value, so, for example, you cannot add a singleton
method to a Fixnum."

Is that the answer you are looking for?
James G. (Guest)
on 2006-06-10 17:01
(Received via mailing list)
On Jun 10, 2006, at 4:16 AM, Guest wrote:

> is there any ways to limit ruby numbers up to certain bytes? all i've
> read is that ruby numbers are limited to host's free memory

Keep watching the Ruby Q....  ;)

James Edward G. II
Suraj N. Kurapati (Guest)
on 2006-06-11 00:40
(Received via mailing list)
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Guest wrote:
> is there any ways to limit ruby numbers up to certain bytes? all i've
> read is that ruby numbers are limited to host's free memory

Use a bit mask to truncate the integer:

irb(main):011:0> ((2 ** 32) - 1)
=> 4294967295
irb(main):012:0> ((2 ** 32) - 1) & 0xFF
=> 255
irb(main):013:0> ((2 ** 32) - 1) & 0xFFFF
=> 65535
irb(main):014:0> ((2 ** 32) - 1) & 0xFFFFFF
=> 16777215
irb(main):015:0> ((2 ** 32) - 1) & 0xFFFFFFFF
=> 4294967295

For negative integers, be sure to preserve the sign by converting
the result back into two's complement form:

irb(main):021:0> -1
=> -1
irb(main):022:0> -1 & 0xFF
=> 255
irb(main):023:0> ~(-1 & 0xFF) + 1
=> -255

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)

iD8DBQFEiy4HmV9O7RYnKMcRAmgSAJ4tCb3MTAGidDfh4lUniVDgJ2coMACeO4a0
x/h1y/QYbKE8VaEzMiyhdMU=
=YkLw
-----END PGP SIGNATURE-----
This topic is locked and can not be replied to.