Sunday, September 30, 2012

Decimal to Binary. How to program?

Sick and tired doing computations how decimal number will be converted in to binary code? Although its not really complicated then, taking much of your time is different. It is not necessary to used logic in manual computation but definitely "yes" in programming. Let me tell you how converting decimal number to binary code is done. For example, decimal number 12 will be converted manually. Use simple division operation.

12/2=6 remainder 0
6/2=3  remainder 0
3/2=1  remainder 1
1/2=0  remainder 1

Reading the reamainders from bottom to top, the binary value of 12 is 1100.

And here is the simple code for it.
import java.util.Scanner;

public class decimalToBinary{
   
    public static void main(String[] args) {
           Scanner sn = new Scanner(System.in);
          
           System.out.print("Enter a Number: ");
           int num = sn.nextInt();
          
           String str ="";
        for(;num>0;){
            int binary = num%2;
            str = Integer.toString(binary) + str;
            num /= 2;
        }
        System.out.println("\nBinary Value: " + str);   
    }   
}


You can try writing a program by doing the example above in vice-versa. (Binary to Decimal).How? Convert binary value 1100 to a decimal, it must be 12 suppostedly. In expanded form, substitute the decimal equivalents of all the symbols, multiply and add is appropriate. 1 1 0 0

1*2^3 + 1*2^2 + 0*2^1 + 0*2^0 = 12

No comments:

Post a Comment