P3 4/21 Binary Overview
Representing data with bits, the consequences of using bits, and binary to decimal conversions.
Learning Objectives
DAT-1.A: Representing Data with Bits
Basic Information
- Bit is short for __ digit, and represents a value of either 0 or 1.
- A byte is 8 bits.
- Sequences of bits are used to represent different things.
- Representing data with sequences of bits is called ___.
Examples
- Boolean variables (true or false) are the easiest way to visualize binary.
- 0 = False
- 1 = True
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)
DAT-1.B: The Consequences of Using Bits to Represent Data
Basic Information
- Integers are represented by a fixed number of bits, this limits the range of integer values. This limitation can result in __ or other errors.
- Other programming languages allow for abstraction only limited by the computers memory.
- Fixed number of bits are used to represent real numbers/limits
Examples
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)
DAT-1.C: Binary Math
Basic Information
- Binary is Base 2, meaning it can only represent values between 0 and 1.
- Decimal is Base 10, meaning it can represent from 0 to 9.
- Conversion between sequences of binary to decimal depend on how many binary numbers there are, their values and their positions.
Examples
- Using 6 bits, we can represent 64 numbers, from 0 to 63, as 2^6 = 64.
- The numbers in a sequence of binary go from right to left, increasing by powers of two from 0 to the total amount of bits. The whole number represented is the sum of these bits. For example:
- 111111
- 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0
- 32 + 16 + 8 + 4 + 2 + 1
- 63
-
Fill in the blanks (convert to decimal)
- 001010 = _
- 11100010 = _
- 10 = _
Hacks & Grading (Due SUNDAY NIGHT 4/23)
- Complete all of the popcorn hacks (Fill in the blanks + run code cells and interact) [0.2 or nothing]
- Create a program to conduct basic mathematical operations with binary sequences (addition, subtraction, multiplication, division) [0.7 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]