Question

I stumbled upon an error that I don't quite understand.

# Ruby 1.8.7
>> [Digest::MD5.hexdigest("http://www.google.com").to_i(16)].pack("N")
RangeError: bignum too big to convert into 'unsigned long'

# Ruby 1.9.3
>> [Digest::MD5.hexdigest("http://www.google.com").to_i(16)].pack("N")
=> "17!@"

Anybody can explain why, and how can I solve this? If no portable solution can be used, I need one for 1.8.7.

Was it helpful?

Solution

In Ruby 1.8+, pack fails if the value is too large - but you can get the same behaviour by only considering the low order bits, by changing:

[Digest::MD5.hexdigest("http://www.google.com").to_i(16)].pack("N")

to

[Digest::MD5.hexdigest("http://www.google.com").to_i(16) % 2**32].pack("N")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top