4. Bitwise Operator:

• Bitwise operator works on bits and performs bit by bit operation.
• Assume if a = 4; and b = 5; Now in the binary format their values will be 0100 and 0101 respectively.
• Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands −Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands –

a = 0100

b = 0101

—————–

a&b =    0100                                                       a|b = 0101

a^b =     0001                                                       ~a  =  1011

Examples: In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary).

Working:

• AND: AND operator symbol is (&). x and y
• If both bits are 1 then returns 1, otherwise returns 0.
• OR: OR operator symbol is (|).  x or y
• If at least one bit is 1 then returns 1, otherwise returns 0.
• XOR: XOR operator symbol is (^). a xor b
• If both bits are different then returns 1, otherwise 0.
• NOT: Bitwise NOT is also known as a complement operator, a symbol is (~).  ~a
•   It is unary and has the effect of ‘flipping’ bits.
• It always converts bits form 1 to 0 and 0 to1.
• Ex: a =   1101
• ~a = 0010
• Bitwise left shift: symbol (<<).
• The left operand’s value is moved left by the number of bits specified by the right operand.
• In left shift operation, bits are transferred to the left side vacant.
• And right side vacant cell fill with 0.
• Ex:
• 2 << 1  à 0010 à (<<) à 0100
• 2 << 2  à 0010 à (<<) à 1000
• Bitwise right shift: symbol (>>).
• The left operand’s value is moved right by the number of bits specified by the right operand.
• And left side vacant cell filled with the sign bit.
• Ex:
• 4 >> 1 à 0100 à (>>) à 0010
• 4 >> 2 à 0100 à (>>) à 0001

Truth table of all gates: