Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

I am using GNU/Linux and GCC compiler

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 ?

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. But I don't know if the result depends on the machine, compiler or OS.

like image 830
smilingbuddha Avatar asked Apr 26 '26 19:04

smilingbuddha


2 Answers

For the & operator (and most other operators), any operands smaller than int will be promoted to int before the operation is evaluated.

From the C99 standard (6.5.10 - describing the bitwise AND operator):

The usual arithmetic conversions are performed on the operands.

(6.3.1.8 - describing the usual arithmetic conversions):

the integer promotions are performed on both operands

(6.3.1.1 - describing the integer promotions):

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.

like image 58
Oliver Charlesworth Avatar answered Apr 29 '26 09:04

Oliver Charlesworth


Regardless of what the language specifies, the answer to the question is that it does not matter whatsoever if the high 24 bits are dropped before the bitwise and is performed, since they're all-zero bits in one operand and thus in the result.

like image 23
R.. GitHub STOP HELPING ICE Avatar answered Apr 29 '26 09:04

R.. GitHub STOP HELPING ICE