number to binary java code example

Example 1: java integer to binary string

int n = 1000;
String s = Integer.toBinaryString(n);

Example 2: int to binary java

String binary = Integer.toBinaryString(num);

Example 3: convert decimal to binary in java

public class DecimalToBinaryExample2{    
public static void toBinary(int decimal){    
     int binary[] = new int[40];    
     int index = 0;    
     while(decimal > 0){    
       binary[index++] = decimal%2;    
       decimal = decimal/2;    
     }    
     for(int i = index-1;i >= 0;i--){    
       System.out.print(binary[i]);    
     }    
System.out.println();//new line  
}    
public static void main(String args[]){      
System.out.println("Decimal of 10 is: ");  
toBinary(10);    
System.out.println("Decimal of 21 is: ");  
toBinary(21);    
System.out.println("Decimal of 31 is: ");    
toBinary(31);  
}}

Example 4: how to get binary value in java

import java.util.*;

class Bin {

    //fields
    private Double number;

    //constructors
    public Bin(){
        number = 0.0;
    }

    public Bin(Double num){
        number = num;
    }

    //methods
    public ArrayList<String> reverseArrayList(ArrayList<String> alist) {
        
        ArrayList<String> array = new ArrayList<String>();

        int x = 0;
        int i = alist.size() - 1;

        while(x < alist.size()){
            array.add(alist.get(i));
            i -= 1;
            x += 1;
        }

        return array;
    }

	//getter methods
    public ArrayList<String> getBinVal(){
        ArrayList<String> binaryVal = new ArrayList<String>();
        ArrayList<String> array = new ArrayList<String>();
        Double num = number;
        Double sol1, check; 

        while( num > 0 ) {

            sol1 = num/2;
            check = sol1 - Math.floor(sol1);

            if(check > 0) {
                binaryVal.add("1");
                num = sol1 - 0.5;
            }

            else {
                binaryVal.add("0");
                num = sol1;
            }
        }

        while(binaryVal.size() < 4) {
            binaryVal.add("0");
        }

        array = reverseArrayList(binaryVal);
        return array;
    }

}

class MainClass {
    
    public static void main(String[] args) {
		
      	//add the number in as a command line argument
        Double num = Double.valueOf(args[0]);
		
      	//create an instance of Bin
        Bin value = new Bin(num);
		
      	//print the binary value
        System.out.println(value.getBinVal());
    }
}

Tags:

Java Example