Binary Numbers

## Popcorn Hack 1: Binary to Decimal Converter

def binary_to_decimal(binary_str):
    decimal = 0
    for i in range(len(binary_str)):
        decimal += int(binary_str[-(i + 1)]) * (2 ** i)
    return decimal

#Get user input
binary_input = input("Enter a binary number: ")
decimal_output = binary_to_decimal(binary_input)
print(f"The decimal representation of {binary_input} is {decimal_output}.")
The decimal representation of 11111 is 31.
## #Popcorn Hack 2: Binary Addition Battle
## How it works:

### Step 1: The game randomly generates two binary numbers (between 0 and 255). Step 2: The user has to add these binary numbers and input the result. Step 3: The game checks if the result is correct and measures how fast the user solved it, providing feedback and points based on performance.

import random
import time

def binary_addition_battle():
    # Generate two random binary numbers (up to 8 bits)
    num1 = bin(random.randint(0, 255))[2:]
    num2 = bin(random.randint(0, 255))[2:]
    
    # Show the binary numbers
    print(f"Add the following binary numbers:")
    print(f"Number 1: {num1}")
    print(f"Number 2: {num2}")
    
    # Start the timer
    start_time = time.time()
    
    # Ask the user for the sum
    user_answer = input("Your answer (in binary): ")
    
    # End the timer
    end_time = time.time()
    
    # Calculate the correct binary sum
    correct_answer = bin(int(num1, 2) + int(num2, 2))[2:]
    
    # Check if the answer is correct
    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()
Add the following binary numbers:
Number 1: 10110000
Number 2: 11010011
Correct! You took 77.15 seconds.
Your score: +10 points!

Question 28:

A text-editing application uses binary sequences to represent each of 200 different characters. What is the minimum number of bits needed to assign a unique bit sequence to each of the possible characters?

A) 4 B) 6 C) 7 D) 8

D

Question 36:

A computer program performs the operation 2 divided by 3 and represents the result as the value 0.6666666667. Which of the following best explains this result?

A) An overflow error occurred. B) The precision of the result is limited due to the constraints of using a floating-point representation. C) The program attempted to execute the operation with the arguments in reverse order. D) The program attempted to represent a floating-point number as an integer.

B

Question 42:

Internet protocol version 4 (IPv4) represents each IP address as a 32-bit binary number. Internet protocol version 6 (IPv6) represents each IP address as a 128-bit binary number. Which of the following best describes the result of using 128-bit addresses instead of 32-bit addresses?

A) 4 times as many addresses are available. B) 96 times as many addresses are available. C) 2 to the fourth power times as many addresses are available. D) 2 raised to the ninety-sixth power times as many addresses are available.

D

Question 44:

A computer program uses 4 bits to represent nonnegative integers. Which of the following statements describe a possible result when the program uses this number representation?

I. The operation 4 plus 8 will result in an overflow error. II. The operation 7 plus 10 will result in an overflow error. III. The operation 12 plus 3 will result in an overflow error.

A) I only B) II only C) II and III only D) I, II, and III

D

## HW 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()
👾 Welcome to Binary Battle Royale! 👾

⚡ Round 1 ⚡
Add these two binary numbers: 1100 + 1000
✅ Correct!

⚡ Round 2 ⚡
Convert this binary number to decimal: 11110
✅ Correct!

⚡ Round 3 ⚡
Subtract these two binary numbers: 10111 - 1
✅ Correct!

🏆 Game Over! 🏆
Your final score: 3/3
🌟 Amazing job! You're a Binary Master!

Explain in 1-2 sentences how to convert a binary number into a decimal number.

To convert a binary number to decimal, just multiply each bit by 2 raised to its position power (starting from 0 on the right) and then add them all up. Basically, you’re stacking powers of 2 wherever there’s a 1.

If you are given the binary number 11111111, what decimal number is that?

255.

Logic Gates

Popcorn Hack What are methods of real-world purpose that using logic gates can implement? Explain deeper if using our listed impacts, explaining why this impact is helpful.

Security systems (alarm circuits) and transportation (traffic light control) both use logic gates. Security systems will go off if a door is activated, but it can be any door, so it would be an OR gate. Traffic lights will use AND gates. For example, AND gates can make sure a green light only turns on if both the timer and a sensor detecting no cross traffic are true.

Popcorn Hack 2 A digital circuit receives three binary inputs: X, Y, and Z. The circuit outputs 1 if and only if X AND Y are both 1, OR Z is 1.

Which of the following expressions represents the circuit’s behavior?

A. (X AND Y) OR Z B. X AND (Y OR Z) C. (X OR Y) AND Z D. NOT(X AND Y) OR Z

A because either A AND Y have to be 1 OR Z has to be one.

## Homework Hack: Authorization System
## Task: Fill in the missing code necessary to implement a Python function that simulates a secure entry system using an AND gate.

## Template:

def secure_entry_system(keycard, pin, voice):
    def AND(a, b, c):
        return a & b & c  # AND logic

    return AND(keycard, pin, voice)

# Test cases
print(secure_entry_system(1, 1, 1))  # Expected Output: 1 (Access Granted)
print(secure_entry_system(0, 1, 1))  # Expected Output: 0 (Access Denied)

## The above is code for a secure entry system - using a keycard and a pin. You’ll notice that to have access into the system, you need to have both a keycard and a pin (And Gate). 
# #Your task is to add another variable (like voice authorization) that is required to have access into the building.
1
0