Convert Integer to Binary in Java

What is Binary?

Binary is a number either 0 or 1, is a base 2-numeral.

Every value of Integer can be represented in binary format in a easy way.

Simply, to convert Integer value to binary value, divide the integer by 2 until it becomes 0., and store the reminder…

  • 0 – 0000
  • 1 – 0001
  • 2 – 0010
  • 3 – 0011
  • 4 – 0100
  • 5 – 0101 and so on..

Java Integer provides inbuilt functions to convert Integer to Binary.

Integer.toBinaryString()

Output

101

Logic to Convert Integer to Binary

The following example explains the logic of how the Integer is easily converted to binary string.

Output:

101

Logic is to simply store the reminder of 2 for the give input.,

Divide the value by 2.,

  • 5%2 = 1
  • 5/2 = 2 (whole value(2 instead of 2.5), as we are capturing the reminder above)

  • 2%2 = 0
  • 2/2 = 1 (whole value) – This value taken to next step until 0

  • 1/2 = 0 (whole value)

Leave a Reply

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