C – Bit wise Operators


C – Bit wise Operators

BIT WISE OPERATORS IN C:

  • These operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits.
  • Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT), ^ (XOR), << (left shift) and >> (right shift).

TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:

truth-table

BELOW ARE THE BIT-WISE OPERATORS AND THEIR NAME IN C LANGUAGE.

  1. & – Bitwise AND
  2. | – Bitwise OR
  3. ~ – Bitwise NOT
  4. ^ – XOR
  5. << – Left Shift
  6. >> – Right Shift
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y=  01010000

All bit wise operations for x and y are given below.
  1. x&y = 00000000 (binary) = 0 (decimal)
  2. x|y = 01111000 (binary) = 120 (decimal)
  3. ~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -41 (decimal)
  4. x^y = 01111000 (binary) = 120 (decimal)
  5. x << 1 = 01010000 (binary) = 80 (decimal)
  6. x >> 1 = 00010100 (binary) = 20 (decimal)
Note:
  • Bit wise NOT : Value of 40 in binary is 00000000000000000000000000000000 00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit wise NOT operation.
  • Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be left shifted by one place. If we use it as “x << 2 “,  then, it means that the bits will be left shifted by 2 places.

EXAMPLE PROGRAM FOR BIT WISE OPERATORS IN C:

In this example program, bit wise operations are performed as shown above and output is displayed in decimal format.

OUTPUT:

AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

Comments