微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

考虑以下代码
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表示负数?

解决方法

按位和按位或按位xor的结果目前在标准中未指定,特别是从未定义了按位这一术语.我们有 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.


结果,这种技术不能用于常量表达,
这将打破大量的代码.

注意到对声明的强调在大多数情况下都能正常工作(二次补充)架构.所以它依赖于底层表示,例如二进制补码.

原文地址:https://www.jb51.cc/c/118735.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐