Saturday, 1 December 2012

Write a Java program to convert positive decimal integer to binary equivalent using bit-wise operators.


package decimaltobinary;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class DecimalToBinary {
 
    public static void main(String[ ] args) throws IOException {
        System.out.print("Enter The Decimal numbber:");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String input = reader.readLine();
        int deci = Integer.parseInt(input);
        Convert toConvert = new Convert();
        toConvert.deciTobinary(deci);
     
    }
}



class Convert
{
    Convert()
    {
 
    }
    void deciTobinary(int decimal)
    {
        System.out.println("Binary Equivalent of "+decimal+" is:" );
        int mask = 1073741824;
       /* Binary Value of 1073741824 is 1000000000000000000000000000000 which is used as masking for logical bit-wise ANDing. Note: int in Java is of 32 bit */
        while(mask > 0)
        {
            if((decimal & mask) > 0)
            {
                System.out.print("1");
            }
            else
            {
                System.out.print("0");
            }
            mask = mask >> 1;
        }
    }
}

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top