Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

program to convert binary to decimal number?

807600Oct 6 2007 — edited Oct 6 2007
I only know how to do a program that converts only 4 numbers, but it to convert any amount of digits the number enters, I think you need to use a loop or something, but I'm not sure how. Could someone please help me? This is my code so far:
import javax.swing.JOptionPane;

public class bintodec {

	public static void main (String[] args) {
	
		String input;
		int number,digit1,digit2,digit3,digit4,result;
		
		input = JOptionPane.showInputDialog ("Enter a binary number.");
		
		number = Integer.parseInt(input);

		digit1 = ((number % 10000) - (number % 10000 % 1000)) / 1000;
		digit2 = ((number % 1000) - (number % 1000 % 100)) / 100;
		digit3 = ((number % 100) - (number % 100 % 10)) / 10;
		digit4 = (number % 10);
		
		result = (digit1 * 8) + (digit2 * 4) + (digit3 * 2) + (digit4 * 1);
		
		System.out.println ( "Binary number: " + input + "\nConverted Decimal Number: " + result);
		
		System.exit( 0 );
		
	} // main
	
} // bintodec
any help is super-appreciated.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 3 2007
Added on Oct 6 2007
4 comments
779 views