Write a program BinaryChanger.java that accepts a 4 bit binary number as a Strin
ID: 3664997 • Letter: W
Question
Write a program BinaryChanger.java that accepts a 4 bit binary number as a String, and converts it into a decimal number. Description: Binary is the base-2 number system, so numbers are represented using two digits (0 or 1) instead of ten (0 through 9, i.e. decimal). In decimal, you have the one's place, ten's place, hundred's place, etc. where each place is a power of ten. In binary, each place is a power of two, so you have the one's place (20), two's place (21), four's place (22), etc.
Example:
Given the number 0101 here's how it is converted to decimal: 0101 = 23 * 0 + 22 * 1 + 21 * 0 + 20 * 1 = 8 * 0 + 4 * 1 + 2 * 0 + 1 * 1 = 5
Given the number 1111: 1111 = 23 * 1 + 22 * 1 + 21 * 1 + 20 * 1 = 8 * 1 + 4 * 1 + 2 * 1 + 1 * 1 = 15
Example Dialog:
Enter a four digit binary number (e.g. "0111") > 0101 0101 converted to decimal is 5
Explanation / Answer
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class DecimalToBinary { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a Binary number"); String str = br.readLine(); long num = Long.parseLong(str); long rem; while (num > 0) { rem = num % 10; num = num / 10; if (rem != 0 && rem != 1) { System.out.println("This is not a binary number,Please enter again"); } } int i = Integer.parseInt(str, 2); System.out.println("Decimal:" + i); }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.