c bitwise and code example

Example 1: bitshift c

int i = 7;    // Decimal 7 is Binary (2^2) + (2^1) + (2^0) = 0000 0111
int j = 3;    // Decimal 3 is Binary         (2^1) + (2^0) = 0000 0011
k = (i << j); // Left shift operation multiplies the value by 2 to the power of j in decimal
              // Equivalent to adding j zeros to the binary representation of i
              // 56 = 7 * 2^3
              // 0011 1000 = 0000 0111 << 0000 0011

Example 2: 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