Contents

  1. ascii.py
  2. ascii_table.py
  3. binaryToDecimal.py
  4. decimalToBinary.py

ascii.py 1/4

[
top][prev][next]
# Conversion of a text message into ASCII
# by Sara Sprenkle

print "This program converts a textual message into a sequence"
print "of numbers representing the ASCII encoding of the message."
print

message = raw_input("Please enter the message to encode: ")

print
print "Here are the ASCII codes:"

for ch in message:
    print ord(ch),

print

ascii_table.py 2/4

[
top][prev][next]
# Create an ASCII table
# by Sara Sprenkle

print "This program prints out the ASCII Table"

print "DEC CHAR"
print "-"*3, "-"*4

for i in xrange(33, 127):
    print "%3d %4s" % (i, chr(i))
    

binaryToDecimal.py 3/4

[
top][prev][next]
# Convert binary numbers to decimal
# by CSCI 111

import sys

# initialize the decimal value of the number
decVal = 0

# get the binary number from the user, as a string
binNum = raw_input("Please enter a binary number: ")

# go through the positions of the binary number
for pos in xrange(len( binNum ) ):
    # compute the exponent
    exp = len(binNum) - pos - 1
    
    # convert the character at this position to an integer
    bit = int(binNum[pos])
    
    # Make sure we have a valid binary number
    if binNum[pos] != "0" and binNum[pos] != "1":
        print binNum, "not a valid binary number"
        sys.exit(1) 
    
    # This is an alternative solution
    #if bit >= 2:
    #    print binNum, "not a valid binary number"
    #    sys.exit(1)
    
    # compute the decimal value of this bit
    val = bit * 2 ** exp
    
    # add it to the decimal value
    decVal += val
    
print binNum, "is", decVal 

decimalToBinary.py 4/4

[
top][prev][next]
# Convert decimal numbers to binary numbers
# by CSCI111

import sys

# Read in the decimal as an integer
decimal = input("Enter a decimal number: ")

# handle error cases
if decimal < 0:
    print "We don't handle negatives"
elif decimal == 0:
    print "0 is 0"
    sys.exit(0)

# save the original decimal value for use in printing later.
origDecimal = decimal

# Initialize the result to the empty string
binNum = ""

# Repeat until the decimal is 0:
while decimal > 0:
    #  result = str(decimal % 2) + result
    binNum = str( decimal % 2) + binNum
    #  decimal = decimal / 2
    decimal = decimal / 2

# Display the result
print origDecimal, "is", binNum

Generated by GNU enscript 1.6.4.