Decimal to binary converter

Today I show you how to write an application which converts decimal numbers to binary

A binary number has only 2 values 1 and 0.Every device use these numbers to transport information or to transform current to digital numbers.

Method 1:

public static void main(String[] args) { // main Method with 1 overloaded parameter

		
		
		
		int erg= 16; // we want to represent 16 as a binary decimal
		String res = " ";
		int Rest;
		
		while(erg > 0) {
			Rest = erg%2; // Modulo operator  example 2%2 = Rest 0,6%2 = 0,5%2 = 1
			erg = erg/2;  // Note 1/2 = 0 because erg variable is defined as Integer
			
			res = res +" "+ Rest;
			
		}
		
	
		int counter = res.length(); // get the numbers of chars of our string variable
		while(counter != 1) {
			counter --;               // Method:charAt(counter) output of chars in string at specific position
			System.out.printf("%c", res.charAt(counter)); //Output "%c" repre-sent each charachter
		}                        
		
 

		
	}

Output: 10000

Method2:

In this method, we use a static method toBinaryString(value) from Integer Class

int value= 16; // we want to represent 16 as a binary decimal

System.out.println(Integer.toBinaryString(value));

Output: 10000

Leave a Reply

Your email address will not be published. Required fields are marked *