How to store a 64 bit integer in two 32 bit integers in Ruby

ⅰ亾dé卋堺 提交于 2019-12-11 05:07:29

问题


As the title says, I'm a little lost on how to accomplish this in Ruby...there are number of topics on how to do this in C or C++. Any ruby experts out there that can chime in on this?


回答1:


The same syntax you'd use in C works in ruby, just drop the typecasts:

n = 0xFFFFFFFFEEEEEEEE
x = (n & 0xFFFFFFFF00000000) >> 32
y =  n & 0xFFFFFFFF
puts x.to_s(16)
# => "ffffffff"
puts y.to_s(16)
# => "eeeeeeee"
v = x << 32 | y
puts v.to_s(16)
# => "ffffffffeeeeeeee"

If you need the values to be in chunks of exactly 32 bits (i.e. you need to speak binary to some external data file or program), then you'll want to use Array#pack and String#unpack to get the right bits.




回答2:


one 64bit integer is not equal to two 32bit integers.

http://en.wikipedia.org/wiki/Integer_(computer_science)



来源:https://stackoverflow.com/questions/4834424/how-to-store-a-64-bit-integer-in-two-32-bit-integers-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!