Java Program To Convert Binary To Decimal
Chapter:
Interview Programs
Last Updated:
19-07-2016 13:43:59 UTC
Program:
/* ............... START ............... */
import java.util.Scanner;
public class JavaBinaryToDecimal {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a binary number: ");
int binarynum = in.nextInt();
int binary = binarynum;
int decimal = 0;
int power = 0;
while (true) {
if (binary == 0) {
break;
} else {
int tmp = binary % 10;
decimal += tmp * Math.pow(2, power);
binary = binary / 10;
power++;
}
}
System.out.println("Binary=" + binary + " Decimal=" + decimal);
}
}
/* ............... END ............... */
Output
Enter a binary number:
111
Binary=0 Decimal=7
Enter a binary number:
1000
Binary=0 Decimal=8
Notes:
-
An easy method of converting decimal to binary number equivalents is to write down the decimal number and to continually divide-by-2 (two) to give a result and a remainder of either a “1” or a “0” until the final result equals zero.
- The binary ("base two") numerical system has two possible values, often represented as 0 or 1, for each place-value.
- decimal (base ten) numeral system has ten possible values (0,1, 2, 3, 4, 5, 6, 7, 8, or 9) for each place-value.
Tags
Convert Binary To Decimal, Java