How do I unpack a number larger than 64 bits in ruby?

无人久伴 提交于 2019-12-06 09:24:45

I think your hunch about how to handle it is right. Unpack doesn't handle Bignums; they're classically fairly tricky specifically because they don't fit in a standard 64-bit int.

You could manually "unpack" it, via something like:

str.unpack("C*").reverse.each_with_index.inject(0) do |sum, (byte, index)|
  sum + byte * (256 ** index)
end

That is, reverse the list of bytes (if on a big endian system), iterate each byte, and multiply its value by 256^position. Ruby's BigNum kicks in once the value gets big enough, and you're able to convert byte strings into very large numbers without a hitch.

You can do the same in chunks of 32-bit (or 64-bit, if the platform supports it) ints, as well:

INT32_MAX = 256 ** [1].pack("L*").size
INT64_MAX = 256 ** [1].pack("Q*").size

str.unpack("L*").reverse.each_with_index.inject(0) do |sum, (byte, index)|
  sum + byte * (INT32_MAX ** index)
end

str.unpack("Q*").reverse.each_with_index.inject(0) do |sum, (byte, index)|
  sum + byte * (INT64_MAX ** index)
end
Gizmomogwai

Thanks a lot for https://stackoverflow.com/a/17014450/204070. Works wonderful for me. The answer could be simplified to:

str.unpack("C*").inject(0) do |sum, (byte, index)|
  sum * 256 + byte
end
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!