Question
Can some help me write this program? Write an interactive Java program to Output an signed decimal number between -128 and 127 corresponding to an
Can some help me write this program?
Write an interactive Java program to Output an signed decimal number between -128 and 127 corresponding to an input 8-bit binary number(a string)in the twos complement system, and
Output an 8-bit binary number (as a string)in the twos complement system corresponding to an input signed decimal number between -128 and 127.
Ive already written a java program (see below) that would convery from bintodec and vice vera, but I need to modify the two methods so that they work for signed integers instead of unsigned integers
import java.util.Scanner;
public class lab2 {
public static void main(String[] args) {
int choice, decimal;
String binary;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("~~~Select any one from below~~~ " // displays menu
+ "1. Convert decimal to binary " + "2. Convert binary to decimal " + "3. Quit ");
choice = sc.nextInt(); // stores the users input as a choice
if (choice == 1) {
System.out.println(" Enter decimal: ");
decimal = sc.nextInt();
binary = decToBin(decimal); // calls dectobin
System.out.println(" " + decimal + " in binary is " + binary + " ");
} else if (choice == 2) {
System.out.println("Enter binary: ");
sc.nextLine();
binary = sc.nextLine();
decimal = binToDec(binary); // calls bintodec
System.out.println(" " + binary + " in decimal is " + decimal + " ");
} else {
System.out.println(" Program terminated"); // program ends
break;
}
}
}
public static String decToBin(int x) {
String bin = ""; // store the bin string
int rem;
for (int i = 0; i < 8; i++) { // runs until you get the 8 bit
rem = x % 2; // rem is remainer of the dec / 2
x = x / 2; // x is the dec divided by 2
bin = rem + bin; // the binary number is the remainder and its stored in bin
}
return bin;
}
public static int binToDec(String s) {
int num = 0;
for (int i = 7; i >= 0; i--) // i is the power
if (s.charAt(i) == '1') // if 1 appears, it takes 2^(7-i)
num = num + (int) Math.pow(2, 7 - i);
return num;
}
}
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