Question
FOR PYTHON 13.1 HW6 Part A: Integer to Binary As we saw in lecture, each number is represented by a binary value. The number of
FOR PYTHON
13.1 HW6 Part A: Integer to Binary
As we saw in lecture, each number is represented by a binary value. The number of bits in the binary number determines the maximum value that can be stored.
For example, an 8 bit number can store from 0 to 255.
We can convert a number to Binary through repeated division.
Take 254 as an example
254 % 2 = 0
254 // 2 = 127
127 % 2 = 1
127 // 2 = 63
63 % 2 = 1
63 // 2 = 31
31 % 2 = 1
31 // 2 = 15
15 % 2 = 1
15 // 2 = 7
7 % 2 = 1
7 // 2 = 3
3 % 2 = 1
3 // 2 = 1
1 % 2 = 1
1 // 2 = 0
When the quotient is equal to 0, we have no more values. The binary value is the remainders read from bottom to top.
11111110
Write a function getInt(question) that asks the user for a number. If the input is not an int, ask again. If the user enters exit, the program will call sys.exit() to exit immediately. Use the question given as the output to the user.
Write a function binaryStr(num,bits) that converts the the number num to a binary string with bits bits. If the number is to big to fit in the bits given, truncate it. Make a string using the "1" and "0" characters.
If the program was asked to make 254 using only 4 bits it will return 1110. The remaining digits don't fit in a 4 bit number.
If the number is smaller than the number of bits, add zeros to pad the front. For example, we can store 0 with 1 bit, but in 8 bits it looks like 00000000.
Develop a main program that asks the user for two inputs and prints the binary value of the number.
Welcome to Binary Printer Enter exit to quit at any time. Enter a Positive Int: cats Not a Number. Enter a Positive Int: 12 Number of Bits: 8 As Binary: 00001100 Enter a Positive Int: 12 Number of Bits: 32 As Binary: 00000000000000000000000000001100 Enter a Positive Int: 900 Number of Bits: 8 As Binary: 10000100 Enter a Positive Int: 900 Number of Bits: 2 As Binary: 00 Enter a Positive Int: 900 Number of Bits: 16 As Binary: 0000001110000100 Enter a Positive Int: 0 Number of Bits: 8 As Binary: 00000000 Enter a Positive Int: 0 Number of Bits: 32 As Binary: 00000000000000000000000000000000 Enter a Positive Int: 45692 Number of Bits: 32 As Binary: 00000000000000001011001001111100 Enter a Positive Int: exit
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started