Java Program to Convert Integer Values into Binary
Given an integer in Java, your task is to write a Java program to convert this given integer into a binary number.
Input: = 45 Output: = 101101 Input: = 32 Output: = 100000
Integers: Integers are numbers whose base value is 10. The Integer or int data type is a 32-bit signed two’s complement integer. Its value-range lies between – 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is – 2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless there is no problem with memory.
Binary Numbers: A binary number is a number expressed in the base-2 numeral. Binary consists of only 2 digits 0 and 1. Two operators are used in the conversion of integers to binary modulo and division to convert the given input into binary numbers.
There are many approaches to convert an integer into binary numbers some of them are discussed here. We will be discussing two of them:
- Using Implementation of Stack
- Using Inbuilt Method- toBinaryString() of the Integer class of Java
1. Using Implementation of Stack
Actually, the binary number consists of only 0 and 1. To convert an integer to binary divide the number by 2 until it becomes 0. In each step take the modulo by 2 and store the remainder into an array or stack. If we store the remainder into an array then print it into reverse order. If we store the remainder into a stack then simply pop one by one element and print it.
Below is the java implementation of the above approach:
Using Stack By Creating Object Vector
2. Using toBinaryString() inbuilt method of the Integer class of Java