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()**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.tutorialflow; public class Example { /** * Binary Conversions - unsigned integers(no negative values) are used. * @param args */ public static void main(String[] args) { // Default Inbuilt function in Java Integer input = 5; String binaryString = Integer.toBinaryString(input); System.out.println(binaryString); } } |

**Output**

**101**

### Logic to Convert Integer to Binary

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.tutorialflow; public class Example { /** * Binary Conversions - unsigned integers(no negative values) are used. * * @param args */ public static void main(String[] args) { Integer input = 5; String result = convertIntegerToBinary(input); System.out.println(result); } /** * Logic is to simply store the reminder of 2 for the given input., */ public static String convertIntegerToBinary(int input) { String result = new String(); while(input>0) { result = input%2+result; input = input/2; } return result; } } |

**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)