COS 100: Introduction to Programming
Fall 2019
Lab 13: Binary numbers
Lab 13A: Binary to decimal
- Write a function
bin2dec
that converts a binary number to decimal. - The input is a binary number represented as a string consisting of
0
s and1
s. - Convert the binary number to decimal, returned as an integer.
- It's okay if your function only works on 8-bit (8-digit) binary numbers (corresponding to integers between 0 and 255).
- (Bonus) Make the function work on binary numbers of any length, not just of length 8.
-
for num in ["01001001", "00010011", "00010000", "01100100", "100101100", "1011100001100"]: print(num, "in decimal is", bin2dec(num))
01001001 in decimal is 73 00010011 in decimal is 19 00010000 in decimal is 16 01100100 in decimal is 100 100101100 in decimal is 300 1011100001100 in decimal is 5900
Lab 13B: Decimal to binary
- Write a function
dec2bin
that converts decimal to binary. - The function accepts as input an integer between 0 and 255. (If a number outside this range is given, complain and quit.)
- Convert the number into an 8-bit binary number, returned as a string (so as to preserve the leading
0
s). -
for num in [73, 19, 16, 100, 300]: print(num, "in binary is", dec2bin(num))
73 in binary is 01001001 19 in binary is 00010011 16 in binary is 00010000 100 in binary is 01100100 300 is not between 0 and 255. Bye.
Challenge Lab 13C: Backwards binary
- Write a program that takes in a decimal integer and prints out the decimal integer you would get if you reversed the binary representation (ignoring leading zeros).
- For example:
17 in binary is 10001 and its reverse is 10001 which is decimal 17 34 in binary is 100010 and its reverse is 010001 which is decimal 17 237 in binary is 11101101 and its reverse is 10110111 which is decimal 183 16 in binary is 10000 and its reverse is 00001 which is decimal 1