Create a program in Java that reads in a 8-bit String, must be read in as such.
ID: 3846696 • Letter: C
Question
Create a program in Java that reads in a 8-bit String, must be read in as such. Then convert that string of 1's and 0's to decimal as if it were encoded using the following representations:
Unsigned
1's Complement
2's Complement
Q(4.4) (2's complement)
1 bit (sign) - 3 bits (exponent: use bias) - 4 bits (significand), implied binary point w/ 1. Also check for 0....
Do not use helper functions, must be done iterating string and modifying an int/long value.
Example Execution (Highlighting is showing the user input):
EDIT: It is a string of 1s and 0s which represents a binary number that needs to be entered and converted to decimal notation
Enter a binary number: 10011010
Unsigned: 154 1's Comp: -101 2's Comp: -102 Q(4.4): -6.375 S-Exp-Sig: -0.40625
Explanation / Answer
import java.util.*;
import java.lang.Math;
public class BinaryString{
public static void main(String []args){
Scanner ob = new Scanner(System.in);
String binStr, rev;
int i, s = 0;
System.out.print("Enter a binary number: ");
binStr = ob.next();
System.out.print("Unsigned: ");
for(i = 0; i < binStr.length(); i++)
{
if(binStr.charAt(i) == '1')
s += Math.pow(2, (binStr.length() - i - 1));
}
System.out.println(s);
s = 0;
System.out.print("1's Comp: ");
for(i = 0; i < binStr.length(); i++)
{
if(binStr.charAt(i) == '0')
s += Math.pow(2, (binStr.length() - i - 1));
}
System.out.println(-s);
System.out.print("2's Comp: ");
System.out.println(-(s+1));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.