C Program#158 – Understanding Bitwise Operators in C.

Program to Understand Bitwise Operators in C. :

Brief Info. : Bitwise Operators

  • Bitwise Operators gives the power to directly manipulate bits (binary digits).
  • C provides six bitwise operators-

    251550

    Category Operator Symbol Operator Name Operation
    Bitwise Logical & Bitwise AND Results 1 if only both operands have 1 otherwise 0. such as 11001000 & 10111000 = 10001000
    | Bitwise OR Results 1 if any one of both operands have 1 otherwise 0. such as 11001000 & 10111000 = 11111000
    ^ Bitwise XOR (Exclusive OR) Performs XOR means results zero only when we have two zeroes or two ones. such as 11001000 ^ 10111000 = 01110000
    Bitwise Shift >> Bitwise Right Shift Shifts Bits to right such as 01110000 >> 1 = 00111000
    << Bitwise Left Shift Shifts Bits to Left such as 01110000 << 1 = 11100000
    Bitwise 1’s (One’s Complement) ~ Bitwise One’s Complement Flips all bits (1 becomes 0 and 0 becomes 1) ~01110000 = 10001111
  • Bitwise AND (&) operator is used (1) to check whether a particular bit in a number is ON or OFF. (2) To turn Off a particular bit in a number.
  • Second Operand in Bitwise AND (&) operator is generally called AND MASK, since it masks (covers) the bits of the first operand and gives resultant bit series, which may be used to check particular bits status.
  • Bitwise OR (|) operator is used to ON a particular bit in a number.
  • Bitwise XOR (^) operator is used to toggle a bit ON or OFF. A number XORed with another number twice gives the orginal number.
  • Bitwise XOR (^) operator is used to toggle a bit ON or OFF. A number XORed with another number twice gives the orginal number.
  • Bitwise RIGHT SHIFT (>>, Bitwise LEFT SHIFT (<<) & One's Complement (~) operator is used in encryption since they changes the original number.
  • Bitwise Operators are used extensively in many areas of Computer Science including Compression, Encryption, Setting Bitfields (flags), Communication Technology (Ports,Checksums,Parity, Stop Bits, Flow Control Algorithms), Embedded Systems etc..
  • Still not understood ? See the proper working example in action below.




Full Well Commented, Self-Explanatory Example Program of the same given below.

Below Here is the Output of the program.



Output of the Program :