Bitwise Operators CS 163 Fall 2018 Java Bitwise
Bitwise Operators CS 163 Fall 2018
Java Bitwise Operators • Java has six bitwise operators: Symbol & | ^ ~ << >> Operator Bitwise AND Bitwise OR Bitwise XOR Bitwise NOT LEFT SHIFT RIGHT SHIFT CS 160, Spring Semester 2014 2
Java AND and OR AND operator (&) A 0 0 1 1 B 0 1 A&B 0 0 0 1 OR operator (|) A 0 0 1 1 CS 160, Spring Semester 2014 B 0 1 A|B 0 1 1 1 3
Java XOR and NOT XOR operator (^) A 0 0 1 1 B 0 1 A^B 0 1 1 0 NOT operator (~) A 0 1 CS 160, Spring Semester 2014 ~A 1 0 4
Binary to Decimal 0 1 2 3 4 5 6 7 Binary 0000 b 0001 b 0010 b 0011 b 0100 b 0101 b 0110 b 0111 b Decimal 8 9 10 11 12 13 14 15 CS 160, Spring Semester 2014 Binary 1000 b 1001 b 1010 b 1011 b 1100 b 1101 b 1110 b 1111 b 5
Binary to Decimal • 0 -9 are used for decimal numbers (base-10): – 149 = 1*102 + 4*101 + 9*100 • 0 -1 are used for binary numbers (base-2): – 1010 b = 1*23 + 0*22 + 1*21 + *20 = 8 + 2 = 10 • Example: – 10111 b in decimal? – 1*24 + 0*23 + 1*22 + 1*21 = 16 + 4 + 2 + 1 = 23 – What is 14 in binary? – 8 + 4 + 2 = 1*23 + 1*22 + 1*21 + 0*20 = 1110 b CS 160, Spring Semester 2014 6
Bitwise Operator Examples • 4 -bit numbers: – 6 & 5 = 0110 b & 0101 b = 0100 b = 4 – 6 | 5 = 0110 b | 0101 b = 0111 b = 7 – 6 ^ 5 = 0110 b ^ 0101 b = 0011 b = 3 – ~6 = ~0110 b = 1001 b = 9 • 8 -bit numbers: – 6 << 3 = 00000110 b << 3 = 00110000 b = 48 (6 * 8) – 48 >> 4 = 00110000 b >> 4 = 00000011 b = 3 (48 / 16) CS 160, Spring Semester 2014 7
Masking Operations • Clearing bits: – x = 00101001 b = 41 – want to clear top 4 -bits – x = x & 00001111 b = x & 15 = 00001001 b = 9 • Setting bits: – x = 00101001 b = 41 – want to set bottom 4 -bits – x = x | 00001111 b = x | 15 = 00101111 b = 47 CS 160, Spring Semester 2014 8
- Slides: 8