In this post, we will show we how to convert a string to binary in Java using two different methods: using the built-in Integer.toBinaryString() method and using bit masking.

To convert a string to binary in Java, we need to convert each character in the string to its numeric value, and then convert that value to its binary representation.

1. Using Bit Masking

We can use bit masking to convert a string to binary in Java, which is a technique to manipulate individual bits in a number using the bitwise operators such as AND, OR, XOR, and SHIFT. The idea is to convert the string to a byte array using the getBytes() method of the String class, which encodes the string into a sequence of bytes. Then convert those bytes into corresponding bits. We can loop through each bit in the byte from left to right using a mask and use the AND operator to check if the bit is 1 or 0, and then append the bit value to a StringBuilder object. This is demonstrated below:

Download  Run Code

 
The advantage of this method is that it allows us to specify the character encoding of the string, which can handle non-ASCII characters or Unicode strings. Note that the getBytes() method uses the platform’s default charset. If the string uses a different character encoding, we may want to pass that character encoding as the argument to the getBytes(encoding) method.

2. Using Integer.toBinaryString() method

The easiest way to convert a string to binary in Java is to use the built-in Integer.toBinaryString() method, which returns binary representation of an integer as a string. The idea is to convert a string into a char array. This can be done with the toCharArray() method. Next, we loop through the char array and convert each char to a binary string using the Integer.toBinaryString() method. We can use the String.format() method to add leading zeros to the result. This approach is demonstrated below.

Download  Run Code

 
However, it uses the default character encoding of the system, and it may not work well with non-ASCII characters or Unicode strings.

That’s all about converting a String to binary in Java.