bitwise operator in c code example

Example 1: bitwise operators explanation in c++

The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1.
The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
The >> (right shift) in C or C++ takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.
The ~ (bitwise NOT) in C or C++ takes one number and inverts all bits of it

Example 2: bitwise operator

#include <stdio.h>
int main()
{
    int a = 12, b = 25;
    printf("Output = %d", a&b);
    return 0;
}

Example 3: bitwise operator

bitwise complement of N = ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)

Example 4: C bitwise

#include <stdio.h>
int main(void) {
  unsigned int a = 60; //Equal to: 0011 1100
  unsigned int b = 13 // Equal to: 0000 1101
  
  int both = a & b //If both are 0, then its a 0, 
  // if both are 1, then its a 1.  //0000 1100
  
  printf("%d\n", both);


}

Tags:

Cpp Example