UNIT FOUR
Converting Binary to Decimal :
1100111₂ = 1 * 2⁶ + 1 * 2⁵ + 0 * 2⁴ + 0 * 2³ + 1 * 2² + 1 * 2¹ + 1 * 2⁰ = 1 * 64 + 1 * 32 + 0 * 16 + 0 * 8 + 1 * 4 + 1 * 2 + 1 * 1 = 64 + 32 + 4 + 2 + 1 = 103
Binary, Octal, Decimal, and Hexadecimal Systems Example :
415 in binary notation 110011111₂ 415 in octal notation 637₈ 415 in decimal notation 415⏨ 415 in hexadecimal notation 19F₁₆
Method Call
<an object>.<method name>(<argument-1>,..., <argument-n>)
Subscript Operator in a Loop Example :
>>> data = "Hi there!" >>> for index in range(len(data)) : print(index, data[index]) 0 H 1 i 2 3 t 4 h 5 e 6 r 7 e 8 !
Reading Text from a File
>>> f = open("myfile.txt", 'r') >>> text = f.read ( ) >>> text 'First line.\nSecond line.\n' >>> print(text) First line. Second line. >>> f = open("myfile.txt", 'r') >>> for line in f: print(line) First line. Second line. >>> f = open("myfile.txt", 'r') >>> while True: line = f.readline( ) if line == "": break print(line) First line. Second Line.
Opens a file object on a file
>>> f = open("myfile.txt", 'w') If the file does not exist, it is created with the given filename. If the file already exists, Python opens it. When an existing file is opened for output, any data already in it are erased.
method write
>>> f.write("First line.\nSecond line.\n") The write method expects a single string argument. If you want the output text to end with a newline, you must include the escape character '\n' in the string.
Slicing Example :
>>> name = "myfile.txt" # The entire string >>> name[0: ] 'myfile.txt' >>> name[0:1] # The first character 'm' >>> name[0:2] # The first two characters 'my' >>> name[ :len(name)] # The entire string 'myfile.txt' >>> name[-3: ] # The last three characters 'txt' >>> name[2:6] # Drill to extract 'file' 'file'
Decrypts
To translate a cipher text to the original plaintext.
in
When used with strings, the left operand of in is a target substring, and the right operand is the string to be searched. The operator in returns True if the target string is somewhere in the search string, or False otherwise. >>> filelist = ["myfile.txt", "myprogram.exe", "yourfile.txt"] >>> for fileName in fileList: if ".txt" in fileName: print(fileName) myfile.txt yourfile.txt
Example of Caesar Cipher :
if the distance value of a Caesar cipher equals three characters, the string "invaders" would be encrypted as "lqydghuv".
Writing Numbers to a FIle
import random f = open("integers.txt", 'w') for count in range(500): number = random.randint(1, 500) f.write(str(number) + '\n') f.close( )
4-1a // The Structure of Strings
-
4-2 // Data Encryption
-
4-4 // String Methods
-
4-5 // Text Files
-
Caesar Cipher
- A very simple encryption method that has been in use for thousands of years. - An encryption method that replaces characters with other characters a given distance away in the character set.
Block Cipher
- An encryption method that replaces characters with other characters located in a two-dimensional grid of characters. - A block cipher uses plaintext characters to compute two or more encrypted characters.
To Convert Binary Numbers to Octal Number :
- Begin at the right and factor the bits into groups of three bits each. - You then convert each group of three bits to the octal digit they represent. - As the size of a number system's base increases, so does the system's expressive power, its ability to say more with less. As bit strings get longer, the octal system becomes a less useful shorthand for expressing them.
How Data Is Encrypted?
- The sender encrypts a message by translating it to a secret code, called a cipher text. - At the other end, the receiver decrypts the cipher text back to its original plaintext form. - Both parties to this transaction must have at their disposal one or more keys that allow them to encrypt and decrypt messages.
To Convert Octal Numbers to and From Binary :
- To convert from octal to binary, you start by assuming that each digit in the octal number represents three digits in the corresponding binary number. - You then start with the leftmost octal digit and write down the corresponding binary digits, padding these to the left with 0s to the count of 3, if necessary. Octal 437 4(100) 3(011) 7(111)
String Methods
>>> s = "Hi there!" >>> len(s) 9 >>> s.center(11) ' Hi there! ' >>> s.count('e') 2 >>> s.endswith("there!") True >>> s.startswith("Hi") True >>> s.find("the") 3 >>> s.isalpha( ) False >>> 'abc'.isalpha ( ) True >>> "326".isdigit ( ) True >>> words = s.split ( ) >>> words ['Hi', 'there!'] >>> " ".join(words) 'Hithere!' >>> " ". join(words) 'Hi there!' >>> s.lower( ) 'hi there!" >>> s.upper( ) 'HI THERE!' >>> s.replace('i', 'o') 'Ho there!' >>> " Hi there! ".strip( ) 'Hi there!'
Data Structure
A compound unit consisting of several data values.
Immutable Data Structure
A data structure in which one cannot insert, remove, or replace the values contained therein.
Invertible Matrix
A data structure used in a block cipher.
Object
A data value that has an internal state and a set of operations for manipulating that state.
Binary Number System
A number system that represents base two numbers, using the digits 1 and 0. Base two number system that feature 0 and 1.
Decimal Number System
A numbers system that represents base ten numbers, using the digits 0 through 9. Also known as the base ten number system.
Mode String
A string argument to the open function, such as 'r' or 'w', that indicates whether the file is being opened for input or output. - 'r' for input files - 'w' for the output files
Bit String
A string containing the binary digits 0 and 1.
Substrings
A string that represents a segment of another string.
len
A string's length is the number of characters it contains. Python's len function returns this value when it is passed a string, as shown in the following session: >>> len("Hi there!") 9 >>>len("") 0 H(0)i(1) (2) t(3)h(4)e(5)r(6)e(7)!(8)
Buffer
An area of computer memory used to transmit data to and from external storage.
Slicing
An operation that returns a subsection of a linear collection, for example, a sublist or a substring. - To extract a substring, the programmer places a colon (:) in the subscript. - An integer value can appear on either side of the colon.
Hexadecimal
Base 16, using the digits 0 through 9 and A through F.
Octal
Base 8
Code for Decimal Number to Binary Number :
Converts a decimal integer to a string of bits decimal = int(input("Enter a decimal integer: ")) if decimal == 0: print(0) else: print("Quotient Remainder Binary") bitString = "" while decimal > 0: remainder = decimal % 2 decimal = decimal // 2 bitString = str(remainder) + bitString print("%5d%8d%12s" % (decimal, remainder, bitString)) print("The binary representation is", bitString) | Enter a decimal integer: 34 | Quotient Remainder Binary 17 0 0 8 1 10 4 0 010 2 0 0010 1 0 00010 0 1 100010 The binary representation is 100010
Code for Binary Number to Decimal Number :
Converts a string of bits to a decimal integer bitString = input( "Enter a string of bits: " ) decimal = 0 exponent = len(bitString) - 1 for digit in bitString: decimal = decimal + int(digit) * 2 ** exponent exponent = exponent - 1 print("The integer value is", decimal) | Enter a string of bits: 1111 | The integer value is 15
The Number 0 Through 8 in Binary :
Decimal Binary 0 | 0 1 | 1 2 | 10 3 | 11 4 | 100 5 | 101 6 | 110 7 | 111 8 | 1000
Subscript Operator Example :
In the following examples, the subscript operator is used to access characters in the string "Alan Turing": >>> name = "Alan Turing" >>> name [0] # Examine the first character 'A' >>> name [3] # Examine the fourth character 'n' >>> name [len(name)] # Oops! An index error! Trackback... >>> name [len(name) - 1] #Examine the last character 'g' >>> name [-1] # Shorthand for the last character 'g' >>> name [-2] # Shorthand for next to last character 'n'
Methods
Operations that are called by name and run on or associated with objects.
Keys
Resources used to encrypt or decrypt data.
Subscript Operator [ ]
The [ ] symbol, which contains an integer or a key, used to access a value in a sequence or a dictionary. <a string>[ <an integer expression> ]
Extension
The characters following the period in a filename, indicating the type of file. - On a Windows file system, a filename ending in ".txt" denotes a human-readable text file, whereas a filename ending in ".exe" denotes an executable file of machine code.
Cipher Text
The output of an encryption process.
Data Encryption
The process of transforming data so that others cannot use it. Examples of such versions are FTPS and HTTPS.
Index
The relative position of a component of a linear data structure or collection.
Plaintext
The source text or input for an encryption process.
Positional Notation
The type of representation used in based number systems, in which the position of each digit denotes a power in the system's base.
Positional Valve
The value resulting from raising a digit at a given position in a number to its base.
split
obtain a list of the words contained in an input string. >>> sentence = input("Enter a sentence: ") Enter a sentence: This sentence has no long words. >>> listOfWords = sentence.split( ) >>> print("There are", len(listOfWords), "words.") There are 6 words. >>> sum = 0 >>> for word in listOfWords: sum += len(word) >>> print("The average word length is", sum / len(listOfWords)) The average word length is 4.5
Sniffing Software
programs that allow the user to spy on data transmissions over a network.
Positional Values Example :
the positional values of the three-digit number are 100 (10²) , 10 (10¹) , and 1 (10⁰) , moving from left to right in the number. 415⏨ = 4 * 10² + 1 * 10¹ + 5 * 10⁰ = 4 * 100 + 1 * 10 + 5 * 1 = 400 + 10 + 5 = 415