当操作系统仅支持 32 位时,如何递增 64 位数字?
我有一个数字存储为长度最多 16 个字符(0 到 F)的字符串。这需要递增并将结果存储为字符串。
最简单的事情是将字符串转换为 int,加一,然后转换回字符串。但是操作系统不支持 64 个号码。还有什么选择呢?
我认为使用两个 32 位整数的手工解决方案是可能的,在这种情况下,这一定是一个常见的场景,但经过一番谷歌搜索后,我找不到任何样板模板代码来完成这样的事情。
更新:抱歉 - 之前应该提到过 - 这是针对 Brew MP C++ 的 - 他们的转换库的 API 仅限于 32 位。
尝试使用 long long 似乎在硬件上一般执行时存在根本性的大问题,使其无法使用。
I have a number stored as a string up to 16 chars (0 to F) in length. This needs to be incremented and the result stored as a string.
Simplest thing would have been to convert the string to an int, increment by one, then convert back to a string. However the OS doesn't support 64 numbers. What's the alternative?
I presume a hand crafted solution using two 32 bit integers is possible, in which case this must be a common scenario, but I couldn't find any boilerplate template code for doing such a thing after a bit of googling.
UPDATE: Sorry - sould have mentioned earlier - This is for Brew MP C++ - their conversion libraries' APIs are limited to 32 bit.
And experimenting with long long seems to have fundamental big time problems in general executing on hardware, making it unusable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以一次增加一位数字。如果数字在“0”和“8”之间,则加一;同样,如果它位于“A”和“E”之间。如果是“9”,则将其设置为“A”。如果它是“F”,则将其设置为“0”并增加左侧的下一个数字。
You can increment one digit at a time. If the digit is between '0' and '8', just add one; likewise if it's between 'A' and 'E'. If it's '9', set it to 'A'. If it's 'F', set it to '0' and increment the next digit to the left.
你的编译器不支持64位长?
您可以使用各种库来支持任意宽度整数,例如 http://gmplib.org/
Your compiler doesn't support a 64-bit long?
You can use a variety of libraries to support arbitrary width integers such as http://gmplib.org/
包含
并使用int64_t< /code> 或
uint64_t
。您甚至可以在 32 位计算机上使用它们。所有这一切都需要一个现代编译器。Include
<cstdint>
and useint64_t
oruint64_t
. You can use them even on 32-bit machines. All that you need a modern compiler.这是 @Mark 在 C++ 中建议的解决方案:
记住使用反向迭代器调用它,因此字符串从右向左递增:
Here is the solution suggested by @Mark in C++:
Remember to call it with reverse iterators, so the string gets incremented from right to left:
这是从我编写的一些 C# 中手工移植的(没有 C++ 编译器) - 因此您可能需要调整它。这适用于低/高类型结构。
This is hand-ported from some C# I wrote (without a C++ compiler) - so you may need to tweak it. This works against a low/high type struct.