Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. Converting a Number from Binary to Decimal:
  2. Topics Covered: reading keyboard input, if statements, nested loops
  3.  
  4. Earlier in the semester we learned the binary and hexadecimal number systems. Your program will take as input a series of “binary digits” as a string and then will compute the equivalent decimal number, which will then be displayed by your main program.
  5.  
  6. To convert a number from base 2 to base 10, we first find the weight of each bit in the binary number. The weight of each bit in the binary number is assigned from right to left. The weight of the rightmost bit is 0. The weight of the bit immediately to the left of the rightmost bit is 1, the weight of the next bit to the left is 2 and so on. Consider the binary number 1001101. The weight of each bit is as follows:
  7.  
  8. Weight 6 5 4 3 2 1 0
  9. 1 0 0 1 1 0 1
  10.  
  11. We use the weight of each bit to find the equivalent decimal number. For each bit, we multiply the bit by 2 to the power of its weight and then add all of the numbers. For the above binary number, the equivalent decimal number is:
  12.  
  13. = 1 * 26 + 0 * 25 + 0 * 24 + 1 * 23 + 1 * 22 + 0 * 21 + 1 * 20
  14. = 64 + 0 + 0 + 8 + 4 + 0 + 1
  15. = 77
  16.  
  17. Remember: to convert a binary number to an equivalent decimal number:
  18. 1. The weight of each bit in the binary number must be determined.
  19. 2. The weight is assigned from right to left.
  20.  
  21. Tasks:
  22. 1. NOTE: your program MUST allow the user to input more than one binary string. You will begin by asking the user if they want to enter a number or quit. IF they select “quit” then no further processing should happen and your program should quit. If they select to input a number your program should do the following with each iteration:
  23. a. Your program must prompt the user for a binary # as a sequence of 1’s and 0’s.
  24. b. Your program will read the user’s input as a String and then must VALIDATE that the string contains ONLY 1’s and 0’s. If it contains any other character an error should be displayed and execution should stop, and you should ask the user if they want to enter another number or quit.
  25. c. If the string is valid, using a loop you will access each character from the string convert it into an integer 1 or 0, and multiply it by the correct power of two, and add it to the sum that represents the decimal number.
  26. d. Your program should display the number input and its correct decimal representation.
  27.  
  28. 2. Your program should ask the user if they want to enter another binary number or quit.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement