5

I want to generate a 64 bit integer in ruby. I know in Java you have longs, but I am not sure how you would do that in Ruby. Also, how many charecters are in a 64 bit number? Here is an example of what I am talking about... 123456789999.

@num = Random.rand(9000) + Random.rand(9000) + Random.rand(9000)

But i believe this is very inefficient and there must be a simpler and more concise way of doing it.

Thanks!

user2351234
  • 965
  • 2
  • 12
  • 20
  • You generally want to inject a seed just once at the start of a program. – Jiminion Aug 01 '13 at 18:16
  • 2
    So you want to generate a random number between -2^64 and 2^64 - 1 ? Or you want to generate a random number with X number of digits. – Rob Wagner Aug 01 '13 at 18:18
  • 2**64 I think would work. – user2351234 Aug 01 '13 at 18:25
  • 1
    There's usually context for a random number. What's it for? For instance `SecureRandom.random_number( 2**64 )` would be appropriate if you want to generate a key or secret. – Neil Slater Aug 01 '13 at 19:54
  • 1
    "How many characters are in a 64-bit number?" That's a problematic question. Character count doesn't have any particular correlation to bitwidth. Plus, it depends on radix. You could store the number 15 _as_ a 64-bit integer, and then the first 60 bits will be `0` and the last 4 will be `1`, but expressed in decimal there's only two characters. Expressed in hex, there's only one character (`F`). – Jazz Aug 01 '13 at 22:46

1 Answers1

12

rand can take a range as argument:

p a = rand(2**32..2**64-1) # => 11093913376345012184
puts a.class #=> Bignum

From the doc: 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...

lobner
  • 593
  • 1
  • 7
  • 15
steenslag
  • 79,051
  • 16
  • 138
  • 171