简体   繁体   English

C ++中8位整数和32位整数之间的按位AND

[英]Bitwise AND between an 8-bit integer and 32 bit integer in C++

If I perform a Bitwise AND between a 8 bit integer ( int8_t ) and 32 bit integer ( int ) will the result be a 8 bit integer or a 32 bit integer? 如果我在8位整数( int8_t )和32位整数( int )之间执行按位AND,结果是8位整数还是32位整数?

I am using GNU/Linux and GCC compiler 我正在使用GNU / Linux和GCC编译器

To put the question slightly differently, before performing the bitwise AND, are the first 24 bits of the 32 bit integer discarded, or is the 8 bit integer first typecast to a 32 bit integer ? 为了稍微改变一下这个问题,在执行按位AND之前,是否丢弃了32位整数的前24位,或者是8位整数首先将类型转换为32位整数?

EDIT: In this little code 编辑:在这个小代码中

#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;
}

I get the output as 4. I would assume that means that the result is a 32 bit integer then. 我得到输出为4.我认为这意味着结果是32位整数。 But I don't know if the result depends on the machine, compiler or OS. 但我不知道结果是否取决于机器,编译器或操作系统。

For the & operator (and most other operators), any operands smaller than int will be promoted to int before the operation is evaluated. 对于&运算符(以及大多数其他运算符),在计算运算之前,任何小于int操作数都将被提升为int

From the C99 standard (6.5.10 - describing the bitwise AND operator): 从C99标准(6.5.10 - 描述按位AND运算符):

The usual arithmetic conversions are performed on the operands. 通常的算术转换是在操作数上执行的。

(6.3.1.8 - describing the usual arithmetic conversions): (6.3.1.8 - 描述通常的算术转换):

the integer promotions are performed on both operands 在两个操作数上执行整数提升

(6.3.1.1 - describing the integer promotions): (6.3.1.1 - 描述整数提升):

If an int can represent all values of the original type, the value is converted to an int ; 如果int可以表示原始类型的所有值,则该值将转换为int ; otherwise, it is converted to an unsigned int . 否则,它将转换为unsigned int These are called the integer promotions. 这些被称为整数促销。

无论语言指定什么,问题的答案是,如果高位24位在按位之前被丢弃并且被执行则无关紧要,因为它们在一个操作数中是全零位,因此在结果中。

8 bit integer is typecast to a 32 bit integer. 8位整数被类型转换为32位整数。 Bitwise operators trigger the usual arithmetic conversions (which means the smaller type is promoted to match the larger). 按位运算符触发通常的算术转换(这意味着较小的类型被提升以匹配较大的类型)。 That's defined in chapter 5.1 of the spec. 这是在规范的第5.1章中定义的。

Integer types smaller than int are promoted to int before any operation is performed on them. 小于int整数类型在对它们执行任何操作之前将提升为int You might want to look at what the CERT Secure Coding Standard says about "understanding integer conversion rules". 您可能想要了解CERT安全编码标准关于“理解整数转换规则”的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM