Binary Numbers and Bit Manipulation Flashcards
What does the bitwise AND (&) operator do?
The AND operator takes two bits and returns 1 if both bits are 1, otherwise returns 0 Think of it like a hose with two knobs – both knobs must be set to on for water to come out (for 1 to return)
2^2
4
1 & 0
0
~ 0000
0000 (0) becomes 1111 (15)
What does the bitwise XOR (^) operator do?
XOR or exclusive or takes two bit and returns 1 if exactly one of the bits is 1, otherwise it returns 0 Think of it like a bag of chips where only one hand can fit. If no one reaches for chips no one gets chips, if both people reach for chips, they can’t fit and no one gets chips either
0011 >> 2 (arithmetic right shift)
0000 (sig digit 0 copied 2 times)
0010 << 2
1000
0 | 1
1
1011 >> 1 (arithmetic shift, two’s complement)
1011 (-8 + 0 + 2 + 1 = -5) 1101 (-8 + 4 + 0 + 1 = -3)
0 & 1
0
Bit manipulation when you want to cancel out matching numbers?
XOR
What happens in an arithmetic right shift?
The least significant bit is lost and the most significant bit is copied N number of shifts
Binary to decimal: 1011 in two’s complement
-8 + 0 + 2 + 1 = -5
1011 >> 1 (arithmetic right shift)
1101 (sig digit 1 copied 1 time)
0101 & 0110
0100
What is two’s complement encoding?
In two’s complement, the leftmost digit is negative, and the rest of the digits are positive. ex: 101 = -4 + 0 + 1 = -3
What happens if a number is encoded using two’s complement and arithmetic right shifted?
The number sign is preserved (negative stays negative)
Binary to Decimal: 1001
8 + 0 + 0 + 1 = 9
What is a bit shift?
Moving each digit in a number’s binary representation left or right
Binary to decimal: 1001 in two’s complement
-8 + 0 + 0 + 1 = -7
~ 0101
0101 (5) becomes 1010 (10)
Binary to Decimal: 0101
0 + 4 + 0 + 1 = 5
What happens to the value of a binary number with a single left shift?
Multiplies the binary number by 2 ex: 0010 << 1 becomes 0100 (2 to 4)
Binary to Decimal: 0111
0 + 4 + 2 + 1 = 7
What does python’s right shift operator (>>) always do?
Arithmetic right shifting
Binary to Decimal: 0110
0 + 4 + 2 + 0 = 6