This is a java program to convert a binary number to decimal number:
Where the concept is quite simple to do so-
Step 1: extract digits from last (using number%10) and then making number = number/10;
Step 2: Digit * 2place value of digitMultiplying the digits from last with the 2 to the power of position of the digit (place value):
Step 3: As seen above adding the each multiplication of Digit * 2place value of digit
Example: 1101 = 20 * 1 + 21 * 0 + 22 * 1 + 23 * 1 = 13.
Where the concept is quite simple to do so-
Step 1: extract digits from last (using number%10) and then making number = number/10;
Step 2: Digit * 2place value of digitMultiplying the digits from last with the 2 to the power of position of the digit (place value):
Step 3: As seen above adding the each multiplication of Digit * 2place value of digit
Example: 1101 = 20 * 1 + 21 * 0 + 22 * 1 + 23 * 1 = 13.
import java.util.Scanner;
class binarytodecimal
{
public static void main(String args[])
{
int bin, dec=0,k=1;
Scanner scanner=new Scanner(System.in);
System.out.println("Enter the binary number : ");
bin=scanner.nextInt();
while(bin!=0)
{
dec=dec+ (bin%10)*k; // extracting the last digit of a binary number and multiplying it with 2 <sup> digits place value</sup>
k*=2;
bin/=10; // removing the last digit of a binary number
}
System.out.println("Decimal number = "+dec);
}
}
No comments:
Post a Comment