c - a >> ((sizeof a) * CHAR_BIT) 是定义的,UB 还是 IDB?

标签 c bit-manipulation bit bit-shift

1. 请考虑以下事项:

unsigned int a, b;

b = a >> ((sizeof a) * CHAR_BIT);

/* or 2nd operand greater than ((sizeof a) * CHAR_BIT) */

这是定义的、未定义的行为还是依赖于实现的行为?

2。 还有一个子问题:

案例asigned int并且它的移位小于其位长度,是有符号位移实现定义或未定义的行为。在这两种情况下:

  1. 右移时:a >> 5
  2. 左移时:a << 5

EDIT 已编辑问题

最佳答案

1.

来自 C99 标准,第 6.5.7 节:

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

所以它是未定义的。

2.

来自同一部分:

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 x 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 x 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

所以对于左移,如果 a 是明确定义的已签名且为正。如果 a 则未定义有符号且为负。

对于右移,如果 a 是明确定义的已签名且为正。如果a,它是实现定义的有符号且为负。

关于c - a >> ((sizeof a) * CHAR_BIT) 是定义的,UB 还是 IDB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7333025/

相关文章:

c - long long 计算的问题

c - 在 C 中以原子方式比较两个整数的最快方法?

c++ - 在查找子集时,元素和元素数量之间的二进制比较背后的逻辑是什么?

java - 如何在 Java 中有效地舍入(floor)整数?

c - 如何从确定的位置检查一组位是否为 0?

assembly - x86 汇编语言高位和低位

sql - Bits vs Char - 存储 3 个互斥标志的最佳方法是什么?

c - 在C中打印字符串的所有排列

c - 具有低/高字和低/高字节的 DWORD 变量

c - 线程传递参数