Java convert decimal to binary number

Decimal is a base 10 number system that we all familiar with, binary is a base 2 number system that computer understands. Computer programs written in various programming languages are converted into binary through compilers. To convert a decimal to a binary number, we divide the decimal number by 2 and keep the remainder 1 or 0 if there is no remainder until we get to 1 divide by 2 equal to 0 with remainder 1. Put together all the remainder including 0s, from the last remainder 1 to the first remainder, and it is the binary equivalent the decimal number.
For example, convert decimal number 291 to a binary number:

  1. 291/2=145…1
  2. 145/2=72….1
  3. 72/2=36…..0
  4. 36/2=18…..0
  5. 18/2=9……0
  6. 9/2=4…….1
  7. 4/2=2…….0
  8. 2/2=1…….0
  9. 1/2=0…….1

100100011 is the binary equivlent of the decimal number 291.

To convert the binary back to decimal:

  1. 1*2^0=1
  2. 1*2^1=2
  3. 0*2^2=0
  4. 0*2^3=0
  5. 0*2^4=0
  6. 1*2^5=32
  7. 0*2^6=0
  8. 0*2^7=0
  9. 1*2^8=256

1+2+0+0+0+32+0+0+256=291

Here is Java program that converts a given decimal to a binary number.

public class DecimalToBinary {

	public static String toBinary(int num)
	{
		String b="";
		int remainder;
		while(num>0)
		{
			remainder = num%2;
			b = Integer.toString(remainder) + b;
			num = num / 2;
		}
		return b;
	}
	
	public static void main(String args[])
	{
		String bin = DecimalToBinary.toBinary(291);
		System.out.println(bin);
	}
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search