A2SV G5 - Bitwise Operation - With Code-Merged
A2SV G5 - Bitwise Operation - With Code-Merged
A2SV G5 - Bitwise Operation - With Code-Merged
Operations 0 1
Lecture Flow
● Pre-requisites
● De nition of Bits
● Bit representation of integers
● Bitwise operators
● Bitwise operators properties
● Bit Masking
● Bit Masking operations
● Python’s built in functions
● Practice questions
● Quote of the day
2
Pre-requisites
No prerequisites folks
3
What are Bits?
Bit is the smallest unit of data in a computer system and
represents a binary digit, which can have one of two values:
0 or 1.
Bit Representation for unsigned?
Bit Representation
Bit Representation for signed?
Bit Representation
2’s Complement
2’s Complement
● A method to represent negative numbers
● Most popular method
● Allows adding negative numbers with the same logic gates as positive
numbers
● Main Idea: x + (-x) = 0
2’s Complement
How to convert number to 2's complement
1. Convert the positive number to binary
2. Flip the bits (1 to 0 and 0 to 1)
3. Add 1
Why Bits?
● Some questions require bit manipulations.
● It can be used to optimize solutions and simplify solutions.
Bit Operators
Bit Operators
● NOT (~)
● AND (&)
● OR (|)
● XOR (^)
● Bit Shifts (<<,>>)
NOT
AND
Check yourself
3&2=?
OR
Check yourself
7|8=?
XOR
Check yourself
4^9=?
Left Shift
Check yourself
1 << 3 = ?
Right Shift
Check yourself
16 >> 3 = ?
num = 10001000100111
1 = 00000000000001
Test 5th Bit
num = 10001000100111
1 = 00000000000001
1<<5 = 00000000100000
10001000100111
&
00000000100000
00000000100000 (!= 0)
Implement
Bit masking operations
Checkpoint
Question #3
def build(i=0):
nonlocal used
if i == len(nums):
ans.append(curr.copy())
return