Question: Convert Binary or Hexadecimal Numbers to Decimal Overview: Converting binary and hexadecimal numbers to decimal by hand is pain! Write a program that'll do this
Convert Binary or Hexadecimal Numbers to Decimal
Overview:
Converting binary and hexadecimal numbers to decimal by hand is pain! Write a program that'll do this for you. It should accept either number, base-2 or base-16 and based on the prefix, 0b and 0x, it should convert to decimal appropriately.
Setup:
Create a class (.java) file called BinHexDec.java
(This can be within a project that contains the other parts of this homework or it can be in separate project on its own)
Features:
ask the user to enter a number in either binary or hex
the number must be prefixed with 0x or 0b for hex and binary respectively
read the input as a string
if the input does not have a valid prefix (X$AAF0) or if it has a valid prefix, but no digits are present after the prefix (only 0x or 0b, without anything after), end the program and say I don't know how to covert that number
if the input contains invalid digits for the specified base (for example F, or 15, for 0b, or base-2), end the program with the message Error parsing base-[either 2 or 16] number
if the input is valid, then convert the number to decimal
you can use Integer.parseInt with a single parameter (that is for the default, decimal)
however you are not allowed to call the two parameter version of parseInt that allows you to use radix
for reference, converting from either a character to an int or a String to an int
Character.getNumericValue(ch) // char to int
ch - 48 // or ch - '0', assuming your character is a digit
Integer.parseInt(s) // string to int, don't use radix for this assignment!
Example Output:
(Converts from hexadecimal to decimal if prefix is 0x)
Please enter a hex (0x)or binary (0b) number:
>0xFFF1
Converting from base-16 to base-10 65521
(Converts from binary to decimal if prefix is 0b)
Please enter a hex (0x) or binary (0b) number:
>0b0101
Converting from base-2 to base-10
5
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
