-
Create an array of int of size 8.
Write a separate method that has an array (assumed to be of size 8)
as its parameter and
initializes it with the following powers of two:
0 1 2 3 4 5 6 7
-----------------------------------------------
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
-----------------------------------------------
Initialize this array using a loop that initializes each value based on the
value to its right
in the array, starting from the last cell of the array. You'll need to set the
last value
directly. Do not use Math.pow here.
Your method does not need to return anything. Any changes you make to the
array will be reflected in the array in your main method since they're
actually the same array (even if the variable names are different).
Call this method from your main method to initialize your 8-element
array.
-
Then,
ask the user for an 8-bit binary number (a number containing only 0s and 1s).
Read
this as a String. You may assume the input contains only 0s and 1s. But if the
user does
not enter an 8-bit number, ask for an input number again until they do.
-
Finally,
compute and display the unsigned value of the 8-bit binary number that the
user input.
Do this by setting up a variable to hold the total value of the number. (What
should the
initial value be for this variable?) Then use a loop that looks at each
character in the input
binary string, one at a time. If any character is 1, then add the
corresponding power of 2
from your array created in the first step to your total value. Output the
total value once
you examine every character in the input binary number.
Example: 100100112 = 128+0+0+16+0+0+2+1 = 14710.
NOTE: if you are comparing characters, include the
single quotes around the 0 and 1: '0', '1'.
-
Typically, binary numbers stored in 8-bits are "signed" integers. This means
that the
leftmost bit is a sign (0 for positive, 1 for negative). If the first bit is
0, then the value of
the number is given by the following 7 bits. If the first bit is 1, then the
value of the
number is obtained by computing the value of the one's complement of the
binary number
and then adding 1. The one's complement is obtained by taking the original
binary
number and replacing 1s with 0s and 0s with 1s.
For example, the binary number 111100002 is -1610 since
the one's complement of
111100002 is 000011112 = 1510 so the value of
111100002 is -(15+1) = -1610.
Revise the program above so the input 8-bit number is treated as an 8-bit
"signed"
integer. The output should be the value of the 8-bit number as a signed
integer.