""" Python functions for MAT 3670, lab 4. """ def hexToBinary(s): """ Convert a hexadecimal string into its binary equivalent. """ hexDigits = {'0': [0, 0, 0, 0], '1': [0, 0, 0, 1], '2': [0, 0, 1, 0], '3': [0, 0, 1, 1], '4': [0, 1, 0, 0], '5': [0, 1, 0, 1], '6': [0, 1, 1, 0], '7': [0, 1, 1, 1], '8': [1, 0, 0, 0], '9': [1, 0, 0, 1], 'a': [1, 0, 1, 0], 'A': [1, 0, 1, 0], 'b': [1, 0, 1, 1], 'B': [1, 0, 1, 1], 'c': [1, 1, 0, 0], 'C': [1, 1, 0, 0], 'd': [1, 1, 0, 1], 'D': [1, 1, 0, 1], 'e': [1, 1, 1, 0], 'E': [1, 1, 1, 0], 'f': [1, 1, 1, 1], 'F': [1, 1, 1, 1]} # Build the result sequence of bits in 4-bit groups result = [] for i in range(len(s)): result = result + hexDigits[s[i]] return result def hexToBinaryDemo(): """ Generate all pairs of 2-digit hexadecimal strings and invoke hexToBinary on each. """ hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] for MSB in hexDigits: for LSB in hexDigits: argument = MSB + LSB print argument, hexToBinary(argument) def binaryToHexDemo(): """ Generate all 8-bit patterns and invoke binaryToHex on each. """ for k in range(2**8): bitPattern = decimalToUnsigned(k, 8) print bitPattern, binaryToHex(bitPattern) def singlePrecisionFloatDemo(L): """ Exercise the singlePrecisionFloat function by invoking it with each hexadecimal pattern in the list L. """ # Iterate over each element in L for hexPattern in L: print hexPattern, singlePrecisionFloat(hexToBinary(hexPattern)) def signedIntegerToFloatDemo(L): """ Exercise the signedIntegerToFloat function by invoking it with each integer in L. """ # Iterate over each element in L for n in L: # get the next value in L and convert it to a 32-bit, signed two's complement value if n < 0: nValue = twosComplement(decimalToUnsigned(-n, 32)) else: nValue = decimalToUnsigned(n, 32) # convert it to a floating point value fValue = signedIntegerToFloat(nValue) # obtain the decimal equivalent of this floating point value dValue = singlePrecisionFloat(fValue) # Show the values of interest print binaryToHex(fValue), n, dValue