c - 不同宽度数据类型上位移运算符的安全性

标签 c bit-manipulation bit-shift bitwise-and

按位运算符从来都不是我的强项。我想知道在使用移位时何时需要显式转换。

例如是i&1 == i%2无论何时 i 都保证为真是无符号整数类型,例如char , unsigned , uint64_t ETC。?我认为问题是 1 是否在i&1隐式转换为宽度类型 sizeof(i) .

作为第二个例子,如果我做 i = 1<<myshift , 我是否需要先显式地转换 1到足够宽的数据类型来存储移位的结果,例如:i = (uint64_t)1<<myshift

myshift的类型在第二个例子中只要它是无符号的就无关紧要?


我认为这些问题的答案是肯定的,是的,是的。特别是第二个示例可以快速检查。但是有人对这些东西有很好的引用吗?来自 C 标准的链接/引用将非常有帮助。

最佳答案

1 是的。奇数位是最不重要的 - 在“1”中打开的那个,无论您选择什么表示。

根据 the standard :

Constraints

2 Each of the operands shall have integer type.

Semantics

3 The usual arithmetic conversions are performed on the operands.

4 The result of the binary & operator is the bitwise AND of the operands (that is, each bit in the result is set if and only if each of the corresponding bits in the converted operands is set).".

2 是的,如果您需要超过 sizeof(int) 个字节(可能是 4 个字节),您就必须这样做。

3 是的。再次标准:

Constraints

2 Each of the operands shall have integer type.

Semantics

3 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.

4 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*2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1*2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

关于c - 不同宽度数据类型上位移运算符的安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16726914/

相关文章:

C++ - 按位不是 uchar 产生 int

将原始加速度计值转换为 12 位数字

C 指针结构,不兼容的类型

c - 如何编写NTP客户端?

c - OpenMP:并行工作负载中无加速

java - Bitwise AND, Bitwise Inclusive OR 问题,在 Java 中

javascript - JS逆向有点值(value)

c - 奇怪的右移位不一致

c - 将整个字符数组移位 N 位

c - 如何在程序集中获取 atof() 函数(来自 msvcrt.dll)的双返回值?