将 uint64 转换为 GMP/MPIR 数字
我在 Windows (MSVC 2010) 上使用 MPIR 2.4.0,并且尝试将无符号 64 位整数添加到 mpz_t 数字。然而MPIR/GMP似乎不支持64位整数和mpz_t之间的直接转换。这是否意味着我必须将 uint64 转换为字符串并通过 mpz_init_set_str 读取它? 这既不是很吸引人,也不是看起来很快——两次转换都是免费的。
我错过了什么或者这里使用的技巧/技巧是什么?
干杯,
菲利普
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如 Banthar 建议的那样,使用 mpz_import,但我建议以下内容不依赖于平台字节序:
As suggested by Banthar use mpz_import, but I'd suggest the following which does not rely on the platform endianness:
使用mpz_import:
编辑:代码根据弗兰克的评论。
Use mpz_import:
EDIT: Code updated according to Frank's comment.
是的,如果您使用的平台 (Windows) 不使用 LP64 模型,则没有函数可以将 64 位整数分配给
mpz_t
。您可以单独分配 64 位整数的高半部分和低半部分,然后将它们加在一起,而不是遍历字符串。仍然不是很干净,但几乎可以肯定更快。编辑:请参阅 Banthar's 答案以获得更好的解决方法。
Yes, if you're on a platform (Windows) that doesn't use the LP64 model, then there is no function to assign a 64-bit integer to a
mpz_t
. Instead of going through a string, you could separately assign the high and low half of the 64-bit integer and then add them together. Still not very clean, but almost certainly faster.Edit: see Banthar's answer for a much better workaround.
在 MPIR 3 上运行一些测试后,似乎 mpz_import 由于某种原因在 64 位值上速度较慢,下面的方法更丑陋,但 IME 表现更好(hi 是 UInt64 的较高 32 位,lo 是较低 32 位)
如果 hi 部分为空,当然你可以走捷径,值得进行测试。
如果它是负的 Int64(有符号),则获取 Abs,执行上述操作,然后对 mp_size 字段求反。
After running some tests on MPIR 3, it appears mpz_import is slower for some reason on 64 bit values, the approach below is uglier, but behaves better IME (hi being higher 32bits and lo being lower 32bits of the UInt64)
If the hi part is null, you can shortcut of course, it can be worth making the test.
If it is a negative Int64 (signed), then get the Abs, do the above and then negate the mp_size field.
MPIR 2.4 引入了对 intmax_t 和 uintmax_t 的支持。请参阅 mpz_set_ux()/sx() 和 mpz_get_ux()/sx()。这些函数在 GMP 中不存在,但在 MPIR 2.4.0 手册中记录。
MPIR 2.4 introduced support for intmax_t and uintmax_t. Please see mpz_set_ux()/sx() and mpz_get_ux()/sx(). These functions don't exist in GMP but are documented in the MPIR 2.4.0 manual.