CPSC120A
Fundamentals of Computer Science I

Lab 19

Binary

Use the command line to create a new directory called lab19 in your labs directory. Make sure all of the .py files that you create for this activity are in that directory.

Parse Integer

Decimal integers can be represented by a computer as either a string or as a number. Both representations are useful. For example, the string representation can be mixed with text for user input and output, but only the numeric representation can be used with the numeric operators, addition, subtraction, etc.

Details

Write a function called parse_integer(decimal_string) in a file called parse_int.py. The function should return an int value that is equivalent to the decimal integer represented with decimal_string. The function should assume that decimal_string consists of only numeric characters, the characters '0' - '9'. The function should not use the built-in function int.

Make sure your program handles all necessary cases gracefully. What additional test cases should you check?

Sample Test Cases

Function Call Expected Output
parse_int('123') 123
type(parse_int('123')) <class 'int'>

Hint

Challenge

The function assumes that all input strings represent a positive integer. Modify the function to also convert strings that represent a negative number.
Parse Integer

All computer memory is binary, so whether an integer is represented as a string or as a number, it is still represented as a number in binary.

Details

Write a function called parse_binary(binary_string) in a file called parse_bin.py. The function should return an int value that is equivalent to the binary integer represented with binary_string. The function should assume that binary_string consists of only the characters '0' and '1'. The function should not use the built-in function int.

Make sure your program handles all necessary cases gracefully. What additional test cases should you check?

Sample Test Cases

Function Call Expected Output
parse_int('101') 5
type(parse_int('101')) <class 'int'>

Hint

Challenge

The function assumes that all input strings represent a positive integer. Unlike decimal numbers, binary numbers typically do not use the minus sign, instead they use 0 and 1 and two's compliment. Modify the function to also convert strings that represent a negative number using two's complement.

Submission

Please show your source code and run your programs for the instructor or lab assistant. Only a programs that have perfect style and flawless functionality will be accepted as complete.