Write a program in MATLAB that allows numbers to be entered in decimal (base 10)
ID: 654092 • Letter: W
Question
Write a program in MATLAB that allows numbers to be entered in decimal (base 10), hexadecimal (base 16), or binary (base 2), and then prints out the number again in all three bases.
To distinguish between different bases we'll say that hexadecimal numbers should always be preceded by a "$" and binary numbers by a "%". Other numbers are assumed to be decimal.
When the program is run it should repeatedly allow a number to be entered and then print it out in all three bases until "q" is typed in. Here's an example of how your program should operate:
Enter #: 45
Decimal: 45
Hexadecimal: 2D
Binary: 101101
Enter #: %101
Decimal: 5
Hexadecimal: 5
Binary: 101
Enter #: $31
Decimal: 49
Hexadecimal: 31
Binary: 110001
Enter #: q
Explanation / Answer
import java.util.Scanner;
public class DecimalToBinary {
public String toBinary(int n) {
if (n == 0) {
return "0";
}
String binary = "";
while (n > 0) {
int rem = n % 2;
binary = rem + binary;
n = n / 2;
}
return binary;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int decimal = scanner.nextInt();
DecimalToBinary decimalToBinary = new DecimalToBinary();
String binary = decimalToBinary.toBinary(decimal);
System.out.println("The binary representation is " + binary);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.