c++ - C++ 中 8 位整数和 32 位整数之间的按位与

标签 c++ c gcc int bit-manipulation

如果我在 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 an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

关于c++ - C++ 中 8 位整数和 32 位整数之间的按位与,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8425118/

相关文章:

c - 为什么我的程序使用 for 循环但现在使用 while 循环?

c++ - 推导(非类型)模板参数类型的编译器方差

c++ - Fedora 17 和 Google Protocol Buffers

c++ - 将模板专门化为嵌套类类型

c++ - 嵌套参数包扩展失败

c++ - 为什么我们不能在内联命名空间之外声明演绎指南?

c - 为客户端收到的消息出现段错误

C++:将枚举作为值还是作为常量引用传递更好?

c - 文件操作问题

c++ - 在 Fedora 14 上编译 C++ 程序时出现编译错误