{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Binary Math\n", "> Applying binary math and operations to real-world progamming\n", "- toc: true\n", "- categories: [student]\n", "- comments: true\n", "- author: Shreya Sapkal, Noor Grewal, Keira Okimoto, Alyssa Ringler, Sabine Sommers, Devon Shepherd\n", "- badges: false\n", "- type: ap\n", "- week: 29" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Binary Recap and Notes\n", "> In the bullet points below, record 5 things that you already knew about binary before this lecture\n", "-\n", "-\n", "-\n", "\n", "> Binary is can be applied in many ways to store, access, and manipulate information. Think of three applications that rely on binary.\n", "-\n", "-\n", "-\n", "\n", "> Why is binary such an effective system for storing information? Why don't computers use the decimal system instead?" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Bitwise Opperations\n", "\n", "Fill in the blank spots below during the lecture\n", " \n", "| Opearator | Name | Action |\n", "| ----------- | ----------- | ----------- |\n", "| & | AND | |\n", "| | OR | |\n", "| ^ | XOR | |\n", "| ~ | NOT | |\n", "| << | Left Shift | |\n", "| >> | Right Shift | |\n", "| >>> | Zero-fill Right Shift | |\n", "\n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "> In this program, the ________________ & (AND), | (OR), ^ (XOR), and ~ (NOT) are used to perform the binary operations on the input numbers. The results are stored in separate variables as ____________. Then, the _______ function is used to convert each decimal result to binary, and the binary strings are stored in separate variables. Finally, the program returns a tuple of tuples, with each inner tuple containing both the decimal and binary result for each operation. The outer tuple is ________ into separate variables for printing, and the results are displayed as both decimal and binary." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AND result: decimal = 2 , binary = 10\n", "OR result: decimal = 58 , binary = 111010\n", "XOR result: decimal = 56 , binary = 111000\n", "NOT result: decimal = -11 , binary = b1011\n" ] } ], "source": [ "def binary_operations(num1, num2):\n", " # Perform the binary operations\n", " and_result_decimal = num1 & num2\n", " or_result_decimal = num1 | num2\n", " xor_result_decimal = num1 ^ num2\n", " not_result_decimal = ~num1\n", "\n", " # Convert results to binary\n", " and_result_binary = bin(and_result_decimal)[2:]\n", " or_result_binary = bin(or_result_decimal)[2:]\n", " xor_result_binary = bin(xor_result_decimal)[2:]\n", " not_result_binary = bin(not_result_decimal)[2:]\n", "\n", " # Return the results as a tuple of tuples\n", " return ((and_result_decimal, and_result_binary),\n", " (or_result_decimal, or_result_binary),\n", " (xor_result_decimal, xor_result_binary),\n", " (not_result_decimal, not_result_binary))\n", "\n", "# Ask the user for input\n", "num1 = int(input(\"Enter the first number: \"))\n", "num2 = int(input(\"Enter the second number: \"))\n", "\n", "# Call the binary_operations function and print the results\n", "and_result, or_result, xor_result, not_result = binary_operations(num1, num2)\n", "print(\"AND result: decimal =\", and_result[0], \", binary =\", and_result[1])\n", "print(\"OR result: decimal =\", or_result[0], \", binary =\", or_result[1])\n", "print(\"XOR result: decimal =\", xor_result[0], \", binary =\", xor_result[1])\n", "print(\"NOT result: decimal =\", not_result[0], \", binary =\", not_result[1])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "> Bitwise operations are used in a variety of applications, particularly in low-level programming and computer science. Some common used of bitwise operations include:\n", "> - Flag Management: Flags are used to keep track of the ______________. Bitwise operations can be used to set, clear, and toggle flags.\n", "> - Bit Manipulation: Bitwise operations can be used to ________________ in a binary number. This is often used to ________ specific bits from a number, set specific bits to a particular value, or flip the value of specific bits.\n", "> - Masking: Masking is used to extract a ______\n", "______ from a binary number. Bitwise operations are commonly used for masking, particularly in low-level programming.\n", "> - Encryption: Bitwise operations can be used in cryptographic applications to scramble and unscramble data. One common application of bitwise operations in encryption is the ______ operation.\n", "> - Graphics: Bitwise operations can be used in computer graphics to manipulate individual ______ on a screen. This can be used to draw shapes, change colors, and create special effects.\n", "> - Networking: Bitwise operations are used extensively in __________ applications, particularly in the handling of IP addresses and port numbers." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Binary to String Conversion" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "> This program defines a string_to_binary function that takes a string as input and returns the binary representation of the string. The function uses a for loop to iterate over each character in the string. For each character, the ord function is used to get its ASCII code, which is then converted to binary using the format function with the '08b' format specifier to ensure that each binary number is 8 digits long. The resulting binary numbers are concatenated to form the final binary string.\n", "\n", "![](images/stringtobinary.png)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The binary representation of 'word' is 01110111011011110111001001100100\n" ] } ], "source": [ "# Binary converter program\n", "\n", "# Function to convert a string to binary\n", "def string_to_binary(string):\n", " binary = ''\n", " for char in string:\n", " binary += format(ord(char), '08b') # Convert the character to binary and append to the binary string\n", " return binary\n", "\n", "# Example usage\n", "word = input(\"Enter a word to convert to binary: \")\n", "binary_word = string_to_binary(word)\n", "print(f\"The binary representation of '{word}' is {binary_word}\")\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "> Many programs use binary conversion, particularly those related to computer science, electrical engineering, and mathematics. Programs that rely on binary conversion include:\n", "> - Networking: Programs that deal with network addresses, such as IP addresses and subnet masks, use binary conversion to represent and manipulate the addresses.\n", "> - Cryptography: Programs that deal with encryption and decryption use binary conversion to encode and decode data.\n", "> - Computer Hardware: Programs that interface with computer hardware, such as drivers and firmware, often use binary conversion to communicate with the hardware at the binary level.\n", "> - Mathematical Applications: Programs that deal with complex calculations and mathematical analysis, such as statistical analysis or machine learning algorithms, may use binary conversion to represent large numbers or complex data sets.\n", "> - Finance: Programs that deal with financial calculations and accounting may use binary conversion to represent fractional amounts or complex financial data." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Binary Search\n", "\n", "- An algorithm made to find an ________ from a list of ________\n", "- Works by dividing the list repeatedly to narrow down which half (the low or high half) that contains the item\n", "- Lists of ________ are often used with binary search\n", "- Binary search makes searching more efficient, as it ensures the program won't have to search through an entire list of items one by one\n", "- List must be sorted\n", "\n", "**What are some situations in which binary search could be used?**\n", "- \n", "- \n", "- \n", "- \n", "\n", "### Real Example of Binary Search\n", "\n", "Binary search operates a lot like a \"guess the number\" game. Try the game and explain how the two are similar." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random \n", "\n", "hid = random.randint(0,100)\n", "gues = 0\n", "def game():\n", " global gues\n", " gues += 1\n", " num = int(input('Pick a number'))\n", " if num < hid:\n", " print('higher')\n", " game()\n", " if num > hid:\n", " print('lower')\n", " game()\n", " if num == hid:\n", " print(hid)\n", " print('You Win !!!')\n", " print('guesses: ', gues)\n", "game()" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Logic Gates\n", "\n", "Accepts inputs and then outputs a result based on what the inputs were\n", "\n", "1. NOT Gate (aka inverter)\n", "\n", "- Accepts a single input and outputs the opposite value.\n", "- Ex: If the input is 0, the output is 1\n", "\n", "2. AND Gates\n", "\n", "- Multiple inputs\n", "- Accepts two inputs. \n", "- If both inputs \"true,\" it returns \"true.\" \n", "- If both inputs are \"false,\" it returns \"false.\"\n", "- What would it return if one input was \"true\" and the other was \"false\"? Discuss and record below.\n", "\n", "- \n", "\n", "3. OR Gates\n", "\n", "- Accepts two inputs.\n", "- As long as one of the two inputs is \"true,\" it returns \"true.\"\n", "- If both inputs are \"false,\" what would the OR gate return? Discuss and record below.\n", "\n", "- \n", "\n", "### Universal Logic Gates\n", "\n", "1. NAND Gate\n", "\n", "- Accepts two inputs.\n", "- Outputs \"false\" ONLY when **both** of its inputs are \"true.\" At all other times, the gate produces an output of \"true.\"\n", "\n", "2. NOR Gate\n", "\n", "- Accepts two inputs.\n", "- Outputs \"true\" only when **both** of its inputs are \"false.\" At all other times, the gate produces an output of \"false.\"\n", "\n", "### Collegeboard Practice\n", "\n", "[Noor's Video](https://vimeo.com/819777768?share=copy)\n", "\n", "![](images/pe29.png)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Hacks\n", "- Take notes and answer the questions above. Make sure you understand the purpose and function of the xample programs. (0.9)\n", " \n", "- Complete this quiz and attach a screen shot of your score below. If you missed any questions, explain why you got it wrong and write a short summary of your understanding of the content. (0.9)\n", " \n", "- As your tangible, create a program that allows a user to input two numbers and an operation, converts the numbers to binary and performs the given operation, and returns the value in decimal values. (0.9)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Applying Binary Math - Calculator Hack\n", "> Calculators use binary math to perform arithmetic operations such as addition, subtraction, multiplication, and division.In a calculator, the binary digits are represented by electronic switches that can be either on or off, corresponding to 1 or 0 respectively. These switches are arranged in groups of eight to form bytes, which are used to represent larger numbers. When a user enters a number into a calculator, the number is converted into binary form and stored in the calculator's memory.To perform an arithmetic operation, the calculator retrieves the numbers from its memory and performs the operation using binary math. \n", "\n", "> For example, to add the binary numbers 1010 and 1101, the calculator would perform the following steps:\n", "> 1. Add the rightmost digits, 0 and 1, which gives a sum of 1.\n", "> 2. Move to the next digit to the left and add the digits along with any carry from the previous step. In this case, we have 1 + 0 + 1, which gives a sum of 10. The carry of 1 is then carried over to the next digit.\n", "> 3. Repeat step 2 for the remaining digits until all digits have been added.\n", "> 4. The result of the addition in this example is the binary number 10111, which is equivalent to the decimal number 23.\n", "\n", "> Similarly, subtraction, multiplication, and division are performed using binary math. The algorithms for these operations are based on the same principles as those used in decimal arithmetic, but with binary digits and powers of 2 instead of decimal digits and powers of 10. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def binary_math(num1, num2, operator):\n", " # Write your calculator function here\n", "\n", "\n", "# Ask the user for input\n", "num1 = int(input(\"Enter the first number: \"))\n", "num2 = int(input(\"Enter the second number: \"))\n", "operator = input(\"Enter the operator (+, -, *, /): \")\n", "\n", "# Call the binary_math function and print the result\n", "result = binary_math(num1, num2, operator)\n", "print(\"Result:\", result)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.9" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "bd385fe162c5ca0c84973b7dd5c518456272446b2b64e67c2a69f949ca7a1754" } } }, "nbformat": 4, "nbformat_minor": 2 }