Base 2 Math and Logic Gates
Base 2 Math and Logic Gates
Popcorn Hack 1
| Example |
Number |
Is it Binary? |
| 1 | 101010 | ✅ Yes |
| 2 | 12301 | ❌ No (has 2 and 3) |
| 3 | 11001 | ✅ Yes |
Popcorn Hack 2
| Example |
Operation |
Binary Numbers |
Answer in Binary |
| 1 | Adding | 101 + 110 | 1011 |
| 2 | Subtracting | 1101 - 1011 | 10 |
| 3 | Adding | 111 + 1001 | 10000 |
Logic Gates
Popcorn Hacks
| Popcorn Hack |
Expression |
Result |
Why? |
| 1 |
True or False and False |
True |
and happens first → False and False = False → True or False = True |
| 2 |
not True and False |
False |
not happens first → not True = False → False and False = False |
| 3 |
True or False and not False |
True |
not happens first → not False = True → False and True = False → True or False = True |
Homework Hack 1
# Function to convert decimal to binary
def decimal_to_binary(decimal_number):
if decimal_number == 0:
return "0"
is_negative = decimal_number < 0
decimal_number = abs(decimal_number)
binary = ""
while decimal_number > 0:
binary = str(decimal_number % 2) + binary
decimal_number = decimal_number // 2
if is_negative:
binary = "-" + binary
return binary
# Function to convert binary to decimal
def binary_to_decimal(binary_string):
is_negative = binary_string.startswith("-")
if is_negative:
binary_string = binary_string[1:]
decimal = 0
for i, digit in enumerate(reversed(binary_string)):
decimal += int(digit) * (2 ** i)
if is_negative:
decimal = -decimal
return decimal
# 🧪 Testing the functions
print("Decimal to Binary Tests:")
print(f"10 → {decimal_to_binary(10)}") # Output: 1010
print(f"-10 → {decimal_to_binary(-10)}") # Output: -1010
print(f"0 → {decimal_to_binary(0)}") # Output: 0
print("\nBinary to Decimal Tests:")
print(f"1010 → {binary_to_decimal('1010')}") # Output: 10
print(f"-1010 → {binary_to_decimal('-1010')}") # Output: -10
print(f"0 → {binary_to_decimal('0')}") # Output: 0
Homework 2
import time
difficulty = input("Enter difficulty (easy, medium, hard): ").lower().strip()
while difficulty != "easy" and difficulty != "medium" and difficulty != "hard":
print("Please enter a valid difficulty level.")
difficulty = input("Enter difficulty (easy, medium, hard): ").lower().strip()
time.sleep(0.5)
print("Difficulty set to:", difficulty)