P3-M 4/21 Binary Overview
A series of binary lessons focusssed on math and conversions.
How to contact us
Join the "coding" channel on slack! That is the only place where we will be answering questions or sending announcements about lessons. If you have a question please contact us there.
How to join
- Click on "add channels" below the list of channels
- Click on "browse channels"
- Search for "coding"
- Click the green "Join" button on the right
Learning Objectives
Practice Questions 1A
- How many bits are in 3 bytes?
- 24
- What digital information can be represented by bits?
- state with one of two possible values. Yes or No, True or False.
- Are bits an analog or digital form of storing data? What is the difference between the two?
- Digital is with a computer and analog is manual or doing it by yourself.
1b
- What is the largest number can be represented by 5 bits?
- 31
- One programing language can only use 16 bits to represent non-negative numbers, while a second language uses 56 bits to represent numbers. How many times as many unique numbers can be represented by the second language?
- First language can represent 2^16 and the seconds is 2^56.
- 5 bits are used to represent both positive and negative numbers, what is the largest number that can be represented by these bits? (hint: different thatn question 1)
- Highest number represented is 15
1c
- What values can each digit of a Base 5 system represent?
- 0 to 4
- What base is Hexadecimal? What range of values can each digit of Hexadecimal represent?
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F.
- When using a base above 10, letters can be used to represent numbers past 9. These letters start from A and continue onwards. For example, the decimal number 10 is represented by the letter A in Hexadecimal. What letter would be used to represent the Base 10 number 23 in a Base 30 system? What about in a Base 50 system?
In a Base 30 system, the number 23 in Base 10 would be denoted by the letter H because in Base 10, H stands for the value 15 and Base 30 has 30 characters (0-9 and A-T). On the other hand, in a Base 50 system, the letter X would be used to represent the Base 10 number 23 because X represents the value 23 in Base 50.
import random
def example(runs):
# Repeat code for the amount of runs given
while runs > 0:
# Assigns variable boolean to either True or False based on random binary number 0 or 1.
boolean = False if random.randint(0, 1) == 0 else True
# If the number was 1 (True), it prints "awesome."
if boolean:
print("binary is awesome")
# If the number was 2 (False), it prints "cool."
else:
print("binary is cool")
runs -= 1
# Change the parameter to how many times to run the function.
example(10)
import math
def exponent(base, power):
# Print the operation performed, turning the parameters into strings to properly concatenate with the symbols "^" and "=".
print(str(base) + "^" + str(power) + " = " + str(math.pow(base, power)))
# How can function become a problem? (Hint: what happens if you set both base and power equal to high numbers?)
exponent(5, 2)
Hacks & Grading (Due SUNDAY NIGHT 4/23)
- Complete all of the popcorn hacks (Fill in the blanks + run code cells and interact + Answer ALL questions) [0.3 or nothing]
- Create a program to conduct basic mathematical operations with binary sequences (addition, subtraction, multiplication, division) [0.6 or nothing]
- For bonus, program must be able to conduct mathematical operations on binary sequences of varying bits (for example: 101 + 1001 would return decimal 14.) [0.1 or nothing]
def binary_addition(x, y):
"""
This function adds two binary sequences and returns the sum as a binary sequence.
"""
max_len = max(len(x), len(y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ''
carry = 0
for i in range(max_len - 1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry != 0:
result = '1' + result
return result.zfill(max_len)
def binary_subtraction(x, y):
"""
This function subtracts two binary sequences and returns the difference as a binary sequence.
"""
max_len = max(len(x), len(y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ''
borrow = 0
for i in range(max_len - 1, -1, -1):
x_bit = int(x[i])
y_bit = int(y[i])
diff = x_bit - y_bit - borrow
if diff < 0:
diff += 2
borrow = 1
else:
borrow = 0
result = str(diff) + result
return result.lstrip('0') or '0'
def binary_multiplication(x, y):
"""
This function multiplies two binary sequences and returns the product as a binary sequence.
"""
x_int = int(x, 2)
y_int = int(y, 2)
result_int = x_int * y_int
return bin(result_int)[2:]
def binary_division(x, y):
"""
This function divides two binary sequences and returns the quotient and remainder as a tuple of binary sequences.
"""
x_int = int(x, 2)
y_int = int(y, 2)
quotient_int = x_int // y_int
remainder_int = x_int % y_int
quotient_bin = bin(quotient_int)[2:]
remainder_bin = bin(remainder_int)[2:]
return (quotient_bin, remainder_bin)
while True:
equation = input("Enter a binary equation (e.g. 101 + 110): ")
parts = equation.split()
if len(parts) != 3:
print("Invalid input. Please enter a binary equation in the format 'binary_num operator binary_num'.")
continue
x = parts[0]
op = parts[1]
y = parts[2]
if op == "+":
result = binary_addition(x, y)
elif op == "-":
result = binary_subtraction(x, y)
elif op == "*":
result = binary_multiplication(x, y)
elif op == "/":
quotient, remainder = binary_division(x, y)
result = f"{quotient} remainder {remainder}"
else:
print("Invalid operator. Please use one of '+', '-', '*', or '/'.")
continue
print(f"{x} {op} {y} = {result}")