Explain Codes LogoExplain Codes Logo

Converting an int to a binary string representation in Java?

java
binary-conversion
integer-to-binary
java-8
Nikita BarsukovbyNikita Barsukov·Aug 22, 2024
TLDR

In Java, you can quickly convert an int to a binary string using the Integer.toBinaryString(i):

String binary = Integer.toBinaryString(23); // Returns "10111", just as fast as Usain Bolt

This is a simple and efficient solution for int to binary conversion, courtesy of the standard Java library.

Diving into the binary pool

Behind the convenient one-liner, there's a whole world to explore. Consider other methods, different scenarios, and unmasking the underlying mechanics.

Let's start cooking: Different recipes for conversion

Stir the mix using a radix

Integer.toString(int i, int radix) provides a flexible method to convert bases:

String binary = Integer.toString(23, 2); // "10111"

Keep in mind, Captain, this will add a minus sign for negative int's along for the ride, not a two's complement!

Manual labor: The DIY loop approach

Master artisanship right here! Need to manually convert without standard library functions? No problem!

StringBuilder binary = new StringBuilder(); int number = 23; while (number > 0) { binary.insert(0, number % 2); // Extract the "essence of binary" i.e. modulo 2 number /= 2; // Then, we mercilessly halve the number }

Pro tip: Don't forget about lonely 0, it has feelings too! Add an edge case.

It's recursion time!

For those who love to plunge down the rabbit hole, here's a recursive method for binary conversion:

String toBinaryString(int number) { if (number == 0) return "0"; // Base case - the foundation of all recursion. return toBinaryString(number >>> 1) + (number & 1); // Recursion, powered by bit shifting magic! }

Dealing with negatives and big boys

Handling negative integers and large numbers requires special attention.

For negative numbers, standard methods yield a signed binary. But, if your heart desires two's complement, manual adjustments or clever bitwise operations are required.

For large integers of long data type, use Long.toBinaryString(long n) which is analogous to Integer.toBinaryString(int n).

The key takeaways

When converting integers to binary strings, focus on:

  • The lonely zeroes and pesky negatives.
  • Efficiency: Using StringBuilder and avoiding overflows.
  • Knowing your Java system inside out.

Sprinkling some magic

How to achieve fixed-length encoding with leading zeros aka binary beautification?

String formattedBinary = String.format("%8s", Integer.toBinaryString(9)).replace(' ', '0'); // Returns "00001001"

String.format() formats your string like a pro photographer, giving you the desired alignment and padding.