Encode and Decode String to Binary Format in Java using Apache Commons Codec
Tags: String BinaryCodec Apache Commons Apache Commons Codec commons-codec
In this Java tutorial, we learn how to use the BinaryCodec class of Apache Commons Codec library to convert a String into a String of ‘0’ and ‘1’ and decode it in Java programs.
How to add Apache Commons Codec library to your Java project
To use the Apache Commons Codec library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'commons-codec:commons-codec:1.15'
To use the Apache Commons Codec library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
To have more information about the Apache Commons Codec library you can visit the library home page at commons.apache.org/proper/commons-codec/
How to encode a String into a String of ‘0’ and ‘1’
In the following Java program, we show you how to use the BinaryCodec.encode() method.
BinaryCodecEncodeExample.java
import org.apache.commons.codec.binary.BinaryCodec;
public class BinaryCodecEncodeExample {
public static void main(String... args) {
String inputString = "Simple Solution";
BinaryCodec binaryCodec = new BinaryCodec();
byte[] outputBytes = binaryCodec.encode(inputString.getBytes());
String outputString = new String(outputBytes);
System.out.println("Input String: " + inputString);
System.out.println("Output String: " + outputString);
}
}
Input String: Simple Solution
Output String: 011011100110111101101001011101000111010101101100011011110101001100100000011001010110110001110000011011010110100101010011
How to decode a String in Binary Codec
In the following Java program, we show you how to use the BinaryCodec.decode() method.
BinaryCodecDecodeExample.java
import org.apache.commons.codec.binary.BinaryCodec;
public class BinaryCodecDecodeExample {
public static void main(String... args) {
String inputString = "011011100110111101101001011101000111010101101100011011110101001100100000011001010110110001110000011011010110100101010011";
BinaryCodec binaryCodec = new BinaryCodec();
byte[] outputBytes = binaryCodec.decode(inputString.getBytes());
String outputString = new String(outputBytes);
System.out.println("Input String: " + inputString);
System.out.println("Output String: " + outputString);
}
}
Input String: 011011100110111101101001011101000111010101101100011011110101001100100000011001010110110001110000011011010110100101010011
Output String: Simple Solution
Happy Coding 😊