In  this tutorial, we will see “How to convert Decimal number to Binary using Java 8?”

How to convert decimal number to binary in java 8

Java 8 – How to convert Decimal number to Binary? Share on X

/**
 * Using Java 8, Convert Decimal Number to Binary
 * @author Deepak Verma
 *
 */

import java.util.stream.IntStream;

public class Convert_Decimal_Number_To_Binary_Java8_Example {

	 public static void main(String[] args) {
	        
		 int decimalNumber = 100;
	        
		 String binaryValue = IntStream.iterate(decimalNumber, a -> a / 2)
	                              .limit(32)
	                              .map(b -> b % 2)
	                              .mapToObj(String::valueOf)
	                              .reduce("", (x, y) -> y + x);
	        
		 System.out.println("The Binary value of " + decimalNumber + " is: " + binaryValue);
	    }
}

 

Output:

The Binary value of 100 is: 00000000000000000000000001100100

How to convert decimal number to binary in java 8

In the above example, It uses IntStream and using it’s iterate method to repeatedly divide the decimal number by number 2, until the result of the division becomes 0. Then, the limit method is used to limit the number of iterations to 32, which is basically the number of bits in an int. After that, map method is used to get the remainder of each division, which is basically the binary digit at that place. After applying map method, now it comes to apply the mapToObj method to convert each binary digit to a string, and finally, it’s the reduce method which is used to concatenate all the binary digits into a single string. And, Then using sysout method, we are printing the resulting binary string to the console.

How to convert decimal number to binary in java 8

Java 8 – How to convert Decimal number to Binary? Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts