我可以在 MSVC++ 中使用 128 位整数吗?

2022-01-12 00:00:00 visual-c++ c++ mfc

我正在使用 Visual Studio 2010 编写 C++/MFC 应用程序,我需要维护一个累积的running total,用于计算平均传输率,如下所示:

I'm coding a C++/MFC application using Visual Studio 2010 and I need to maintain a cumulative running total that will be used to calculate an average transfer rate, as such:

//Let's assume that INT128 is a 128-bit integer type
static INT128 iRunningTotal = 0;
static INT128 iCounter = 0;

LONGLONG iteration_get_current_average(LONGLONG iRate)
{
    //May be called repeatedly...
    iRunningTotal += iRate;
    iCounter++;

    //Calculate the current average
    return iRunningTotal / iCounter;
}

我搜索了 C++ 128 位整数,几乎所有人们建议使用 Boost 库的地方.嗯,这是一种可能性,但我不熟悉它,并且不会在我的项目中的其他任何地方使用它.

I searched for C++ 128-bit integer and pretty much everywhere people suggest using Boost library. Well, that's a possibility, but I'm not familiar with it and don't use it anywhere else in my project.

除了 Boost,我很好奇,有没有办法用纯 C/C++ 做到这一点?

So Boost aside, I'm curious, is there a way to do this with pure C/C++?

推荐答案

我将抛??开这是否是个好主意,或者你测量的物理量是否在理论上可能超过 2^ 的问题63,或 10^19 左右.我相信你有你的理由.那么在纯 C/C++ 中你有哪些选择呢?

I shall leave aside the question of whether it's a good idea, or whether the physical quantity you're measuring could even in theory ever exceed a value of 2^63, or 10^19 or thereabouts. I'm sure you have your reasons. So what are your options in pure C/C++?

答案是:不多.

  • 128 位整数不是任何标准的一部分,我所知道的编译器也不支持它们.
  • 64 位双精度将为您提供动态范围(10^308 左右).如果您不需要确切的答案,这是一个很好的选择.不幸的是,如果您有一个包含足够多的零的数字,然后向其添加一个,它就不会改变.
  • 浮点处理器原生支持 80 位双精度,这为您提供了 63 位尾数以及扩展的动态范围.

那么,自己动手做 128 位整数运算怎么样?你真的必须是一个受虐狂.做加法和减法很容易(注意你的进位),并且稍微考虑一下,做乘法并不难.除法完全是另一回事.这非常困难,并且可能的结果是出现类似于 1990 年代 Pentium 错误的错误.

So, how about roll-your-own 128 bit integer arithmetic? You would really have to be a masochist. It's easy enough to do addition and subtraction (mind your carries), and with a bit of thought it's not too hard to do multiplication. Division is another thing entirely. That is seriously hard, and the likely outcome is bugs similar to the Pentium bug of the 1990s.

您可以毫无困难地将计数器累积为两个(或更多)64 位整数.然后将它们转换为双精度数以进行最后的计算.这应该不会太难.

You could probably accumulate your counters in two (or more) 64 bit integers without much difficulty. Then convert them into doubles for the calculations at the end. That shouldn't be too hard.

那之后恐怕要去图书馆购物了.您提到了 Boost,但是周围有更多专业的库,例如 cpp-bigint.

After that I'm afraid it's off to library shopping. Boost you mentioned, but there are much more specialised libraries around, such as cpp-bigint.

不出所料,这个问题之前有人问过并且有很好的答案:表示C++ 中的 128 位数字.

Not surprisingly, this question has been asked before and has a very good answer: Representing 128-bit numbers in C++.

相关文章