如果我在 8 位整数 (int8_t
) 和 32 位整数 (int
) 之间执行按位与,结果将是 8 位整数或 32 位整数整数?
我正在使用 GNU/Linux 和 GCC 编译器
换句话说,在执行按位与之前,是丢弃 32 位整数的前 24 位,还是先将 8 位整数类型转换为 32 位整数?
编辑:在这段小代码中
#include <iostream>
#include <stdint.h>
int main()
{
int i=34;
int8_t j=2;
std::cout<<sizeof((i&j))<<std::endl;//Bitwise and between a 32 bit integer and 8 bit integer
return 0;
}
我得到的输出为 4。我假设这意味着结果是一个 32 位整数。但我不知道结果是否取决于机器、编译器或操作系统。
最佳答案
对于 &
运算符(以及大多数其他运算符),任何小于 int
的操作数都将在运算前被提升为 int
.
来自 C99 标准(6.5.10 - 描述按位与运算符):
The usual arithmetic conversions are performed on the operands.
(6.3.1.8 - 描述通常的算术转换):
the integer promotions are performed on both operands
(6.3.1.1 - 描述整数促销):
If an
int
can represent all values of the original type, the value is converted to anint
; otherwise, it is converted to anunsigned int
. These are called the integer promotions.
关于c++ - C++ 中 8 位整数和 32 位整数之间的按位与,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8425118/