Binary Base Homework and Popcorn hacks
Popcorn Hack #1
# Binary to Decimal Calculator
def binary_to_decimal(binary_str):
try:
decimal_value = int(binary_str, 2)
return decimal_value
except ValueError:
return "Invalid binary input. Please enter a valid binary number."
# Example usage
binary_input = input("Enter a binary number: ")
decimal_output = binary_to_decimal(binary_input)
print(f"The decimal equivalent of binary {binary_input} is {decimal_output}.")
The decimal equivalent of binary 110101011 is 427.
Popcorn Hack #2
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: 101101
Number 2: 111111
Correct! You took 31.05 seconds.
Your score: +10 points!
Homeowork Hack #1
To convert a binary number to decimal, multiply each bit by 2^n (where n is the position of the bit from right to left, starting at 0) and then add all the results together.
For the binary number 11111111, the decimal equivalent is: 255