Bitwise Operators in C
Bitwise operators are used to manipulate one or more bits from integral operands like char, int, short, long.
Bitwise Operators in C There are six bit operators: bitwise AND(&) bitwise OR(|) bitwise XOR(^) bitwise complement(~) left shift(<<) right shift(>>)
Bitwise Operators in C Bitwise and: c1 & c2 # include main() { char c1 = 4,c2 = 6,c3 ; c3 = c1 & c2; printf("\n Bitwise AND i.e. c1 & c2 = %d",c3); } Bitwise AND i.e. c1 & c2 = 4 Suppose c1 = 4, c2 = 6; The value of c1 & c2 is interpreted: &
Bitwise Operators in C Bitwise or: c1 | c2 # include main() { char c1 = 4,c2 =6,c3 = 3; c3 = c1 | c2; printf("\n Bitwise OR i.e. c1 | c2 = %c",c3); } Bitwise OR i.e. c1 | c2 = ? Suppose c1 = 4, c2 = 6; The value of c1 | c2 is interpreted as follows: |
Bitwise Operators in C Bitwise XOR: c1 ^ c2 # include main() { char c1 = 4,c2 = 6,c3 = 3; c3 = c1 ^ c2; printf("\n Bitwise XOR i.e. c1 ^ c2 = %c",c3); } Suppose c1 = 4, c2 = 6; The value of c1 ^ c2 is interpreted as follows: ^
Bitwise Operators in C Complement: ~ # include main() { char c1 = 4,c2 = 6,c3 = 3; c3 = ~c1; printf("\n ones complement of c1 = %c",c3); } Suppose c1 = 4, c2 = 6; The value of ~ c1 is interpreted as follows: ~
Bitwise Operators in C Left shift operator # include main() { char c1 = 1,c2 = 2,c3 = 3; c3 = c1<<2; printf("\n left shift by 2 bits c1 << 2 = %c",c3); } c3 = c1 << 2; The bits are shifted left by two places. c1 is It is shifted 2 bits to the left ** While shifting, the high-order (left) bits are discarded. The vacuum on the right side is filled with 0s.
Bitwise Operators in C Right shift operation # include main() { char c1 = 1,c2 = 2,c3 = 3; c3 = c1>>2; printf("\n right shift by 2 bits c1 >> 2 = %c",c3); }
Bitwise Operators in C Bitwise AND xi yi xi &1 yi Variable b3 b2 b1 b0 x y z = x & y
Bitwise Operators in C Bitwise OR xi yi xi |1 yi Variable b3 b2 b1 b0 x y z = x | y
Bitwise Operators in C Bitwise XOR xi yi xi ^1 yi Variable b3 b2 b1 b0 x y z = x ^ y
Bitwise Operators in C Bitwise NOT xi ~1 xi Variable b3 b2 b1 b0 x z = ~x