为什么不在 C++ 中强制执行 2 的补码?

2022-01-09 00:00:00 binary standards c++

新的 C++ 标准仍然拒绝指定整数类型的二进制表示.这是因为 C++ 的实际实现不使用 2 的补码算法吗?我觉得很难相信.是因为委员会担心未来硬件的进步会使比特"的概念过时吗?再次难以置信.任何人都可以对此有所了解吗?

The new C++ standard still refuses to specify the binary representation of integer types. Is this because there are real-world implementations of C++ that don't use 2's complement arithmetic? I find that hard to believe. Is it because the committee feared that future advances in hardware would render the notion of 'bit' obsolete? Again hard to believe. Can anyone shed any light on this?

背景:我在一个评论线程中两次感到惊讶(Benjamin Lindley 对 this 的回答问题).首先,来自 piotr 的评论:

Background: I was surprised twice in one comment thread (Benjamin Lindley's answer to this question). First, from piotr's comment:

有符号类型的右移是未定义的行为

Right shift on signed type is undefined behaviour

其次,来自 James Kanze 的评论:

Second, from James Kanze's comment:

当赋值给 long 时,如果值不适合 long,则结果为实现定义

when assigning to a long, if the value doesn't fit in a long, the results are implementation defined

在我相信它们之前,我必须在标准中查找这些.它们的唯一原因是适应非 2 的补码整数表示.为什么?

I had to look these up in the standard before I believed them. The only reason for them is to accommodate non-2's-complement integer representations. WHY?

推荐答案

(C++20 现在强制使用 2 的补码表示,请注意有符号算术的溢出仍然未定义,并且移位继续具有未定义和实现定义的行为一些情况.)

( C++20 now imposes 2's complement representation, note that overflow of signed arithmetic is still undefined and shifts continue to have undefined and implementation defined behaviors in some cases.)

  • 定义未定义的东西的一个主要问题是编译器是在假设未定义的情况下构建的.更改标准不会更改编译器,并且审查这些以找出假设的位置是一项艰巨的任务.

  • A major problem in defining something which isn't, is that compilers were built assuming that is undefined. Changing the standard won't change the compilers and reviewing those to find out where the assumption was made is a difficult task.

即使在 2 补码机器上,您的品种也可能比您想象的要多.两个例子:有些没有符号保持右移,只有一个引入零的右移;DSP 的一个共同特点是饱和算法,分配一个超出范围的值会将其限制在最大值,而不仅仅是丢弃高位.

Even on 2 complement machine, you may have more variety than you think. Two examples: some don't have a sign preserving right shift, just a right shift which introduce zeros; a common feature in DSP is saturating arithmetic, there assigning an out of range value will clip it at the maximum, not just drop the high order bits.

相关文章