Decimal and binary are two different number systems used to represent values, with decimal using ten digits (0–9) and binary using only two digits (0 and 1). Converting a decimal number to binary is a fundamental operation in computer science and programming.
Example 1:
Input: Decimal Number = 12
Output: Binary Number = 1100
Example 2:
Input: Decimal Number = 17
Output: Binary Number = 10001
The Integer class provides the toBinaryString() method to convert integer to its binary string representation.
Steps:
public static String toBinaryString(int decimal)
Example
public class Main {
// Method for converting a decimal number to a binary number
public String decimalToBinary(int deciNum) {
// Use Integer.toBinaryString() method
String result = Integer.toBinaryString(deciNum);
return result;
}
public static void main(String[] args) {
Main obj = new Main(); // creating an object of class Main
int num = 12;
System.out.println("The binary representation of decimal number " + num + " is: " + obj.decimalToBinary(num));
num = 17;
System.out.println("The binary representation of decimal number " + num + " is: " + obj.decimalToBinary(num));
num = 0;
System.out.println("The binary representation of decimal number " + num + " is: " + obj.decimalToBinary(num));
}
}
Output:
The binary representation of decimal number 12 is: 1100 The binary representation of decimal number 17 is: 10001 The binary representation of decimal number 0 is: 0
A standard Java integer can only contain 32 bits. Thus, the do-while loop runs at most 32 times (the toBinaryString() method internally uses a do-while loop to do the conversion). Thus, the iteration of the loop does not depend on the input number, making the execution time constant, which is O(1). The String result can contain at most 32 characters, as the do-while loop runs at most 32 times. Thus, space complexity is also constant, which is O(1).
The method calculates each bit of the binary representation of the decimal number using Math.pow(). It determines the number of bits required to represent the decimal number and then iterates through each bit position, calculating the bit value based on its position.
Step 1: Create a StringBuilder object to store the result (binary representation). If the decimal number is 0, return "0" as its binary representation.
Step 2: With the help of base-2 logarithm, find the count of bits needed to represent the decimal number. Store the count in a variable (bitCount in our case).
Step 3: Iterate Through Each Bit Position (for (int i = bitCount - 1; i >= 0; i--)):
Step 4: Find the value of the bit by performing an AND operation between the decimal number and the computed bit value. If the result is 0, the bit at that position is 0; otherwise, it is 1.
Step 5: Append the result found in the previous step ('0' or '1') to the StringBuilder object.
Step 6: Convert the StringBuilder to a String and return it as the binary representation.
Example
public class Main {
// Method to convert a decimal number to binary representation
public static String decimalToBinary(int deciNum) {
// Check if the decimal number is 0
if (deciNum == 0) {
return "0"; // If the decimal is 0, return "0" as a binary representation
}
// Calculate the number of bits needed to represent the decimal number
int bitCount = (int) (Math.log(deciNum) / Math.log(2)) + 1;
// Creating an object of the StringBuilder class for storing
// the binary representation
StringBuilder sbObj = new StringBuilder();
// Iterate through each bit position from the most significant bit to the least significant bit
for (int i = bitCount - 1; i >= 0; i--) {
// Calculating the bit value for
// the current (ith) position
int bitValue = (int) Math.pow(2, i);
// Check if the bit is set in the decimal number
if ((deciNum & bitValue) == 0) {
sbObj.append('0'); // If the bit is not set, append '0'
} else {
sbObj.append('1'); // If the bit is set, append '1'
}
}
// converting string builder to string and returning the string
return sbObj.toString();
}
public static void main(String[] args) {
Main obj = new Main(); // creating an object of class Main
int num = 12;
System.out.println("The binary representation of decimal number " + num + " is: " + obj.decimalToBinary(num));
num = 17;
System.out.println("The binary representation of decimal number " + num + " is: " + obj.decimalToBinary(num));
num = 0;
System.out.println("The binary representation of decimal number " + num + " is: " + obj.decimalToBinary(num));
}
}
Output:
The binary representation of decimal number 12 is: 1100 The binary representation of decimal number 17 is: 10001 The binary representation of decimal number 0 is: 0
The total number of bits of an integer cannot exceed 32 in Java. Thus, the for loop can at most iterate 32 times, and this execution time does not scale with the value of the input number. Thus, the time complexity of the program is O(1). Also, the StringBuilder object can append 32 characters, which also does not depend on the input number, making the space complexity of the program O(1).
The approach employs a recursive algorithm to convert a decimal number to its binary representation. It divides the decimal number by 2 recursively and constructs the binary representation digit by digit.
Step 1: Check if the decimal number is 0 or not; if 0, display "0" as its binary representation.
Step 2: For decimal numbers larger than 1, recursively reduce the number by dividing it by 2. Use non-tail recursion here. The last line of the recursive method should be the display statement for displaying the remainder of the decimal number when divided by 2.
Example
public class Main {
public void decimalToBinary(int num) {
if (num == 0)
{
// For a decimal number 0, the binary representation is also 0
System.out.println("0");
}
else
{
// a utility method for finding the
// decimal representation of a non-zero decimal number
decimalToBinaryUtil(num);
System.out.println();
}
}
// Recursive method for converting and displaying binary
// representation of a decimal. Here, it uses linear recursion.
public void decimalToBinaryUtil(int num)
{
if (num == 0) return; // terminating condition of the recursive calls
// Recursive call with num / 2
decimalToBinaryUtil(num / 2);
// Displaying remainder on return path.
// Internally, it uses a stack here.
System.out.print(num % 2);
}
public static void main(String[] args) {
Main obj = new Main(); // creating an object of class Main
int num = 12;
System.out.print("The binary representation of decimal number " + num + " is: ");
obj.decimalToBinary(num);
num = 17;
System.out.print("The binary representation of decimal number " + num + " is: ");
obj.decimalToBinary(num);
num = 0;
System.out.print("The binary representation of decimal number " + num + " is: ");
obj.decimalToBinary(num);
}
}
Output:
The binary representation of decimal number 12 is: 1100 The binary representation of decimal number 17 is: 10001 The binary representation of decimal number 0 is: 0
In every recursive call, the number is divided by 2, making the time complexity of the program O(log2(n)). Also, each recursive call uses a stack that can grow up to a maximum depth of log2(n), which makes the space complexity of the program O(log2(n)), where n is the input decimal number.
This method employs a stack data structure to store the binary digits of the decimal number in reverse order. It iterates through the decimal number, extracting each bit using bitwise AND operation, and pushes the bits onto the stack. After processing all bits, it pops them from the stack to construct the binary representation.
Steps:
Example
import java.util.Stack;
public class Main {
// Method to convert a decimal number to binary representation using a stack
public static String decimalToBinary(int decimal) {
// Check if the decimal number is 0
if (decimal == 0) {
return "0"; // If the decimal is 0, return "0" as binary representation
}
// Create a stack to store binary digits
Stack stack = new Stack<>();
// Iterate through the decimal number until it becomes 0
while (decimal != 0) {
// Extract the least significant bit by performing a bitwise AND with 1
char bit = (decimal & 1) == 0 ? '0' : '1';
// Push the bit onto the stack
stack.push(bit);
// Right shift the decimal number by 1 to process the next bit
decimal >>= 1;
}
// Create a StringBuilder to construct the binary representation
StringBuilder binary = new StringBuilder();
// Pop bits from the stack to construct the binary representation
while (!stack.isEmpty()) {
binary.append(stack.pop());
}
// Return the binary representation as a String
return binary.toString();
}
public static void main(String[] args) {
int decimal = 27; // Example decimal number
// Print the binary representation of the decimal number
System.out.println("Binary representation of " + decimal + " is: " + decimalToBinary(decimal));
}
}
Output:
Binary representation of 27 is: 11011
We can convert decimal to binary in Java using custom logic.
Example
public class Main {
// Method to convert decimal to binary
public static void toBinary(int decimal) {
int binary[] = new int[40]; // Create an array to store binary digits
int index = 0; // Initialize index to track the position of binary digits
// Iterate until the decimal is greater than 0
while (decimal > 0) {
binary[index++] = decimal % 2; // Store remainder (binary digit) in the array
decimal = decimal / 2; // Update decimal by dividing it by 2
}
// Print binary representation
for (int i = index - 1; i >= 0; i--) {
System.out.print(binary[i]); // Print binary digits in reverse order
}
System.out.println(); // Print new line
}
public static void main(String args[]) {
System.out.print("Decimal of 10 is: ");
toBinary(10); // Convert decimal 10 to binary
System.out.print("Decimal of 21 is: ");
toBinary(21); // Convert decimal 21 to binary
System.out.print("Decimal of 31 is: ");
toBinary(31); // Convert decimal 31 to binary
}
}
Output:
Decimal of 10 is: 1010 Decimal of 21 is: 10101 Decimal of 31 is: 11111
Step 1: Create an integer array for storing the conversion result.
Step 2: Divide the input number by 2 and keep the remainder in the array.
Step 3: Update the number by storing the quotient in it (number = number / 2).
Step 4: Using a loop, repeat the above two steps until the number is greater than zero.
Step 5: Display the array in reverse order.
Example
public class Main
{
static int j = 0;
// method for converting decimal to binary
public int[] decimalToBinary(int num)
{
// if decimal number is 0, return null
if(num == 0)
{
return null;
}
j = 0;
int n = num;
int countDigit = 0;
// loop for counting the number of digits
while (n > 0)
{
n = n / 2;
countDigit = countDigit + 1;
}
// array for storing the result (binary number)
int[] binaryNumArr = new int[countDigit];
while (num > 0)
{
// Storing remainder in binary array
binaryNumArr[j] = num % 2;
// updating num by storing the quotient
num = num / 2;
j = j + 1;
}
return binaryNumArr;
}
// Method for displaying the result (binary number)
public void display(int n, int arr[])
{
if(arr == null)
{
System.out.print("The binary representation of decimal number " + n + " is: 0");
}
else
{
System.out.print("The binary representation of decimal number " + n + " is: ");
// iterating the array in the reverse order
for (int i = j - 1; i >= 0; i--)
System.out.print(arr[i] + " ");
System.out.println();
}
}
public static void main (String[] args)
{
int num = 12;
Main obj = new Main(); // creating an object of the class Main
int res[] = obj.decimalToBinary(num);
obj.display(num, res);
num = 17;
res= obj.decimalToBinary(num);
obj.display(num, res);
num = 0;
res= obj.decimalToBinary(num);
obj.display(num, res);
}
}
Output:
The binary representation of decimal number 12 is: 1 1 0 0 The binary representation of decimal number 17 is: 1 0 0 0 1 The binary representation of decimal number 0 is: 0
The time complexity of the above program is O(log2(n)) because it takes O(log2(n)) time to find the number of digits in a number. The space complexity of the above program is also O(log2(n)). This is because of the size of the array for storing the bits of the decimal number, which takes O(log2(n)), where n is the decimal number.
We request you to subscribe our newsletter for upcoming updates.