Skip to the content.

Binary homework

Binary homework + popcorn hacks and notes

POpcorn Hack #1:

def binary_to_decimal(binary_str):
    decimal = 0
    for i in range(len(binary_str)):
        # Start from the rightmost bit
        decimal += int(binary_str[-(i + 1)]) * (2 ** i)
    return decimal

# Get user input
binary_input = input("Enter a binary number: ").strip()
decimal_output = binary_to_decimal(binary_input)
print(f"The decimal representation of {binary_input} is {decimal_output}.")

Popcorn Hack #2:

import random
import time

def binary_addition_battle():
    # Generate two random binary numbers (8 bits)
    num1 = format(random.randint(0, 255), '08b')
    num2 = format(random.randint(0, 255), '08b')
    
    print(f"Add the following binary numbers:")
    print(f"Number 1: {num1}")
    print(f"Number 2: {num2}")
    
    start_time = time.time()
    user_answer = input("Your answer (in binary): ").strip()
    end_time = time.time()
    
    correct_answer = format(int(num1, 2) + int(num2, 2), 'b')
    
    if user_answer == correct_answer:
        print(f" Correct! You took {end_time - start_time:.2f} seconds.")
        print(f" Your score: +10 points!")
    else:
        print(f" Oops! The correct answer was {correct_answer}.")
        print(f" Your score: -5 points.")

# Run the game
binary_addition_battle()

Homework Hack

import random
import time

def binary_addition(a, b):
    return bin(int(a, 2) + int(b, 2))[2:]

def binary_subtraction(a, b):
    if int(a, 2) < int(b, 2):
        return "Error"
    return bin(int(a, 2) - int(b, 2))[2:]

def decimal_to_binary(n):
    return bin(n)[2:]

def binary_to_decimal(b):
    return int(b, 2)

def binary_battle_royale():
    print("👾 Welcome to Binary Battle Royale! 👾")
    score = 0
    total_rounds = 3

    for round_num in range(1, total_rounds + 1):
        print(f"\n⚡ Round {round_num} ⚡")
        mode = random.choice(["addition", "subtraction", "dec_to_bin", "bin_to_dec"])

        if mode == "addition":
            num1 = bin(random.randint(0, 15))[2:]
            num2 = bin(random.randint(0, 15))[2:]
            print(f"Add these two binary numbers: {num1} + {num2}")
            user_answer = input("Your answer (binary): ").strip()
            correct_answer = binary_addition(num1, num2)
            if user_answer == correct_answer:
                print("✅ Correct!")
                score += 1
            else:
                print(f"❌ Incorrect. The correct answer was {correct_answer}.")

        elif mode == "subtraction":
            num1_val = random.randint(8, 31)
            num2_val = random.randint(0, num1_val)
            num1 = bin(num1_val)[2:]
            num2 = bin(num2_val)[2:]
            print(f"Subtract these two binary numbers: {num1} - {num2}")
            user_answer = input("Your answer (binary): ").strip()
            correct_answer = binary_subtraction(num1, num2)
            if user_answer == correct_answer:
                print("✅ Correct!")
                score += 1
            else:
                print(f"❌ Incorrect. The correct answer was {correct_answer}.")

        elif mode == "dec_to_bin":
            decimal_number = random.randint(0, 31)
            print(f"Convert this decimal number to binary: {decimal_number}")
            user_answer = input("Your answer (binary): ").strip()
            correct_answer = decimal_to_binary(decimal_number)
            if user_answer == correct_answer:
                print("✅ Correct!")
                score += 1
            else:
                print(f"❌ Incorrect. The correct answer was {correct_answer}.")

        elif mode == "bin_to_dec":
            binary_number = bin(random.randint(0, 31))[2:]
            print(f"Convert this binary number to decimal: {binary_number}")
            user_answer = input("Your answer (decimal): ").strip()
            correct_answer = str(binary_to_decimal(binary_number))
            if user_answer == correct_answer:
                print("✅ Correct!")
                score += 1
            else:
                print(f"❌ Incorrect. The correct answer was {correct_answer}.")

    print("\n🏆 Game Over! 🏆")
    print(f"Your final score: {score}/{total_rounds}")
    if score == total_rounds:
        print("🌟 Amazing job! You're a Binary Master!")
    elif score >= total_rounds // 2:
        print("👍 Good effort! Keep practicing!")
    else:
        print("💡 Don't worry — review the rules and try again!")

# --- Start the game ---
binary_battle_royale()

Binary to Decimal Explanation

To convert a binary number to a decimal number:

  • Start from the rightmost digit.
  • Multiply each binary digit (0 or 1) by 2 raised to the power of its position number.
  • Add up all the results to get the decimal number.

Example:

Binary number: 11111111

Calculation: 11111111 in binary equals 255 in decimal.