Hi I am trying to write an app that inputs an integer containing only 0s and 1s (a binary integer) and prints its decimal equivalent. I am aware that there are some very short ways to do this but as a beginner I am writing this to show the process. I am trying to use the remainder and division operators to complete this. Here is what I have, is there a different route I can take? Any help will be greatly appreciated! thanks
Code:import java.util.Scanner; public class BinarytoDecimal { public static void main(String[] args) { int r; int s = 0; int p = 1; Scanner in = new Scanner(System.in); System.out.println("Binary to Decimal"); System.out.println("Enter a Binary Number which is to be converted");//ask to input the number which is to be converted int n= in.nextInt(); while(n > 0) { r = n % 10; n = n / 10; if(r!= 0 && r!= 1) { System.out.println("This is not a binary number.!!!"); System.out.println("Please try once again.!!!"); System.exit(0);//exits if the number is non binary } } System.out.print("Binary="+n); { int temp = n; while(n>0) { r=n%10; s=s+(r*p); p=p*2; n=n/10; } System.out.print("converted to Decimal Number="+s);//generates output {}// Need ending brackets! } // End of main() }} // End of class
Any suggestions would help..PS I know there is an api to do this simple also. But I am trying to show the process
You need to use multiplication and addition to go from binary to decimal, not modulus and division. You should probably accept the binary as a string.
Okay now I have this..What is wrong now. I need to find correct placement and format to inform the user to enter the binary integers..etc
Code:public static long binaryToDecimal(String binary) throws NumberFormatException { // Initialize result to 0 long res = 0; // Do not continue on an empty string if (binary.isEmpty()) { throw new NumberFormatException("Empty string is not a binary number"); } // Consider each digit in the string for (int i = 0; i < binary.length(); i++) { // Get the nth char from the right (first = 0) char n = binary.charAt(binary.length() - (i+1)); // Check if it's a valid bit if ((n != '0') && (n != '1')) { // And if not, die horribly throw new NumberFormatException("Not a binary number"); } else if (n == '1') { // Only add the value if it's a 1 res += Math.round(Math.pow(2.0, i)); } } return res; }
res = res*2 + n.
Where does that need to be
Ok I figured it out!
Thanks WingedPanther!!
No problem![]()
How would I go about saving this thread or what ever is needed to keep it accessible to me ? (I have to do the same sort of thing in class in a few weeks and I think looking this over then would help)
It's saved on the server.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks