Bitwise Operators in C Bitwise Operators in C
Bitwise Operators in C
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: c 1 & c 2 • • • • # include<stdio. h> main() { char c 1 = 4, c 2 = 6, c 3 ; c 3 = c 1 & c 2; printf("n Bitwise AND i. e. c 1 & c 2 = %d", c 3); } Bitwise AND i. e. c 1 & c 2 = 4 Suppose c 1 = 4, c 2 = 6; The value of c 1 & c 2 is interpreted: 0000 0100 & 0000 0110 --------0000 0100
Bitwise Operators in C • Bitwise or: c 1 | c 2 • • • • # include<stdio. h> main() { char c 1 = 4, c 2 =6 , c 3 = 3; c 3 = c 1 | c 2; printf("n Bitwise OR i. e. c 1 | c 2 = %c", c 3); } Bitwise OR i. e. c 1 | c 2 = ? Suppose c 1 = 4, c 2 = 6; The value of c 1 | c 2 is interpreted as follows: 0000 0100 | 0000 0110 -------0000 0110
Bitwise Operators in C • Bitwise XOR: c 1 ^ c 2 • • • • # include<stdio. h> main() { char c 1 = 4, c 2 = 6, c 3 = 3; c 3 = c 1 ^ c 2; printf("n Bitwise XOR i. e. c 1 ^ c 2 = %c", c 3); } Suppose c 1 = 4, c 2 = 6; The value of c 1 ^ c 2 is interpreted as follows: 0000 0100 ^ 0000 0110 -------0000 0010
Bitwise Operators in C • Complement: ~ • • • # include<stdio. h> main() { char c 1 = 4, c 2 = 6, c 3 = 3; c 3 = ~c 1; printf("n ones complement of c 1 = %c", c 3); } Suppose c 1 = 4, c 2 = 6; The value of ~ c 1 is interpreted as follows: ~ 0000 0100 -------1111 1011
Bitwise Operators in C • Left shift operator • # include<stdio. h> • main() • { • char c 1 = 1, c 2 = 2, c 3 = 3; • • • c 3 = c 1<<2; printf("n left shift by 2 bits c 1 << 2 = %c", c 3); } c 3 = c 1 << 2; The bits are shifted left by two places. c 1 is 0000 0100 It is shifted 2 bits to the left 0001 00** While shifting, the high-order (left) bits are discarded. The vacuum on the right side is filled with 0 s.
Bitwise Operators in C Right shift operation # include<stdio. h> main() { char c 1 = 1, c 2 = 2, c 3 = 3; c 3 = c 1>>2; printf("n right shift by 2 bits c 1 >> 2 = %c", c 3); • } • •
• • • Bitwise Operators in C Bitwise AND xi yi 0 0 0 1 1 Variable b 3 x 1 y 1 z=x&y 1 xi &1 yi 0 0 0 1 b 2 b 1 1 0 0 b 0 0
• • • Bitwise Operators in C Bitwise OR xi yi xi |1 yi 0 0 1 1 1 0 1 1 Variable b 3 b 2 x 1 1 y 1 0 z=x|y 1 1 b 1 0 1 1 b 0 0
• • • Bitwise Operators in C Bitwise XOR xi yi 0 0 0 1 1 Variable b 3 x 1 y 1 z=x^y 0 xi ^1 yi 0 1 1 0 b 2 b 1 1 0 0 1 1 1 b 0 0
Bitwise Operators in C • • Bitwise NOT xi ~1 xi 0 1 1 0 Variable b 3 x 1 1 z = ~x 0 0 b 2 0 1 b 1 0 1 b 0
- Slides: 13