在Ruby中模拟int64溢出 [英] Emulating int64 overflows in Ruby

查看:107
本文介绍了在Ruby中模拟int64溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个很长的程序员,但是刚接触Ruby.我正在尝试移植一种称为CheckRevision的算法,该算法用于在登录Battle.net的在线游戏服务之前检查游戏文件的完整性.

I'm a long time programmer but new to Ruby. I'm trying to port an algorithm called CheckRevision used for checking integrity of game files before loggin into Battle.net's online gaming service.

该算法使用给定的公式对文件进行哈希处理".无需无聊的细节,它会不断修改值为64位整数的值abc,或者在我从Java long移植的参考实现中.我的实现对于前几次迭代是正确的,但是当int64应该环绕它时,它变成了BigNum.

The algorithm makes a "hash" of the files with a given formula. Without boring details, it's constantly modifying the values a, b and c which are 64-bit integers, or in the reference implementation I'm porting from, a Java long. My implementation is correct for the first few iterations but when the int64 should wrap around it becomes a BigNum instead.

将FixNum限制为64位的正确方法是什么,还是应该使用其他类型?

What's the proper way to restrict a FixNum to 64bit, or should I be using a different type?

推荐答案

在某些情况下,即使在64位平台上,Ruby MRI在内部也将64位整数表示为Bignums(由于实现细节,Fixnums仅63位长在64位平台上,在32位平台上为31位长).因此,使用二进制和"运算符&:

64-bit integers are represented in Ruby MRI as Bignums internally even on 64-bit platforms in some cases (due to implementation details, Fixnums are only 63 bit long on 64-bit platform sand 31 bit long on 32-bit platforms). Hence, it will be much more faster to use binary "and" operator &:

ruby-1.9.2-p290 :001 > a = 2**128 + 1256231
 => 340282366920938463463374607431769467687 
ruby-1.9.2-p290 :002 > a & (2 ** 64 - 1)
 => 1256231 
ruby-1.9.2-p290 :003 > a & 0xffffffffffffffff
 => 1256231 

最后一个变种有点丑陋,但是也更快,因为Ruby MRI缺少固定的文件夹.如果您要在循环中执行002子句,则每次都会计算2**64 - 1.

The last variant is a bit uglier, but also faster, too, as Ruby MRI lacks constant folders. If you'd do the 002 clause in a loop, it would compute 2**64 - 1 each time).

Ruby MRI是Ruby的正式版本("Matz Ruby实现"),即我们大多数人使用的普通" Ruby.我在这里列出的详细信息可能会也可能不会应用到其他实现中,但是二进制和"通常比任何平台或语言上的模运算符都快或快.

Ruby MRI is an official ("Matz Ruby Implementation") variant of Ruby, i.e. "plain" Ruby which most of us use. The details I've listed here may or may not apply this way to other implementations, but binary "and" is generally faster or as fast as modulo operator on any platform or language.

这篇关于在Ruby中模拟int64溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆