Write an application that inputs an integer containing only 0s and 1s (i.e., a b
ID: 3629597 • Letter: W
Question
Write an application that inputs an integer containing only 0s and 1s (i.e., a binary integer) and prints its decimal equivalent. [Hint: Use the remainder and division operators to pick off the binary number's digits one at a time, from right to left. In the decimal number system, the rightmost digit has a positional value of 1 and the next digit to the left a positional value of 10, then 100, then 1000, and so on. The decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. In the binary number system, the rightmost digit has a positional value of 1, the next digit to the left a positional value of 2, then 4, then 8, and so on. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8, or 1 + 0 + 4 + 8 or, 13].Explanation / Answer
binary : it will store the binary value entered by the user decimal : it will store the final decimal value after all the conversions bit : it will store the multipliers 1, 2, 4, 8, 16 and so on initially we set bit = 1 decimal = 0 in line 20; the value entered by the user in assigned to BINARY Now lets begin the conversion : this loop will continue till the value stored in binary gets exhausted. It is important to keep in mind that we will keep on cutting the value stored in the BINARY variable one digit from right each time as we proceed. 1st iteration [ binary = 11000000 ; decimal = 0 ; bit = 1] line 26: decimal = decimal + [remainder (binary / 10 )] * bit so decimal = 0 + 0*1 = 0 line 27 : binary = binary / 10 [u see , the remainder has been cut off; so the new value of binary = 1100000 (1 zero less) line 27 : bit = bit * 2 so now bit has increased to 2 ---------------------------------------------------------- 2nd iteration : [binary = 1100000; decimal = 0; bit =2] repeat the above steps, the value stored in binary will become still smaller by 1 digit. the new value in bit will become 4 and decimal will remain 0; because in line 25 again u multiply bit by 0 (remainder) --------------------------------------- carry on this way ultimately you will get binary = 11 bit = 64 decimal = 0 + 1 * 64 = 64 final iteration: binary = 1 bit = 128 decimal = 64 + 1*128 = 192 at the end of this iteration binary = 0; so loop terminates Hope it is clear now :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.