C programming - bitwise AND operator

ht‮:spt‬//www.theitroad.com

The bitwise AND operator & in C programming is used to perform a bitwise AND operation between two integer operands. It compares the corresponding bits of both operands and sets the resulting bit to 1 if both bits are 1, and 0 otherwise.

Here is an example of using the bitwise AND operator:

#include <stdio.h>

int main() {
  int num1 = 5; // 101 in binary
  int num2 = 3; // 011 in binary
  int result = num1 & num2;

  printf("result = %d\n", result);

  return 0;
}

In this example, we declared two integer variables num1 and num2 and initialized them with the values 5 and 3, respectively. We used the bitwise AND operator to perform a bitwise AND operation between num1 and num2, and stored the result in the integer variable result. The binary representation of num1 is 101, and the binary representation of num2 is 011, so the result of the bitwise AND operation is 001, which is equal to 1 in decimal.

The output of the program will be:

result = 1

The bitwise AND operator is useful in situations where we need to extract or manipulate individual bits of an integer. For example, we can use the bitwise AND operator with a mask to extract a specific set of bits from an integer.

#include <stdio.h>

int main() {
  int num = 0x0F; // 00001111 in binary
  int mask = 0x03; // 00000011 in binary
  int result = num & mask;

  printf("result = %d\n", result);

  return 0;
}

In this example, we declared an integer variable num and initialized it with the hexadecimal value 0x0F, which is equivalent to the binary value 00001111. We also declared an integer variable mask and initialized it with the hexadecimal value 0x03, which is equivalent to the binary value 00000011. We used the bitwise AND operator to extract the last two bits of num, which is equal to 00000011 in binary. The result of the bitwise AND operation is 00000011, which is equal to 3 in decimal.

The output of the program will be:

result = 3

In summary, the bitwise AND operator & in C programming is used to perform a bitwise AND operation between two integer operands. It compares the corresponding bits of both operands and sets the resulting bit to 1 if both bits are 1, and 0 otherwise. The bitwise AND operator is useful in situations where we need to extract or manipulate individual bits of an integer.