gpt4 book ai didi

c++ - 有符号整数类型的按位运算结果是否定义明确?

转载 作者:可可西里 更新时间:2023-11-01 18:36:46 25 4
gpt4 key购买 nike

考虑这段代码:

using integer = int; // or any other fundamental integral type
using unsigned_integer = typename std::make_unsigned<integer>::type;
constexpr integer bits = std::numeric_limits<unsigned_integer>::digits;
integer value = -42; // or any value
integer mask = static_cast<integer>(1)<<static_cast<integer>(bits-1);
bool result_and = value & mask;
bool result_or = value | mask;
bool result_xor = value ^ mask;

我想知道这些操作是如何按照标准定义的。我能保证在所有架构上得到相同的结果吗?我确定在所有体系结构上对符号位进行操作,其中正数的符号位为 0,负数的符号位为 1

最佳答案

按位与、按位或和按位异或的结果目前在标准中未明确规定,特别是术语按位从未定义。我们有defect report 1857: Additional questions about bits 涵盖了这个问题并说:

The specification of the bitwise operations in 5.11 [expr.bit.and], 5.12 [expr.xor], and 5.13 [expr.or] uses the undefined term “bitwise” in describing the operations, without specifying whether it is the value or object representation that is in view.

Part of the resolution of this might be to define “bit” (which is otherwise currently undefined in C++) as a value of a given power of 2.

决议是:

CWG decided to reformulate the description of the operations themselves to avoid references to bits, splitting off the larger questions of defining “bit” and the like to issue 1943 for further consideration.

这导致合并 defect report 1943: Unspecified meaning of “bit” .

左移有符号类型的结果将取决于底层表示。我们可以从 defect report 1457: Undefined behavior in left-shift 中看出这一点这使得它很好地定义为左移到符号位并说:

The current wording of 5.8 [expr.shift] paragraph 2 makes it undefined behavior to create the most-negative integer of a given type by left-shifting a (signed) 1 into the sign bit, even though this is not uncommonly done and works correctly on the majority of (twos-complement) architectures:

...if E1 has a signed type and non-negative value, and E1 ⨯ 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

因此,这种技术不能用在常量表达式中, 这将破坏大量代码。

注意对声明的强调在大多数情况下都正确(二进制补码)架构。因此它取决于底层表示,例如二进制补码。

关于c++ - 有符号整数类型的按位运算结果是否定义明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33251441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com