Fortunately, the Java APIs provide a fairly simple way of translating your binary bytes back into the original characters.
String char = (char)Integer.parseInt(string, 2)
The string is one byte(8 bits) of a the binary code. The 2 represents that we are currently in base 2. For this to work, you need to feed the above code chunks of your binary in 8 bit portions.
However, the function Integer.toBinaryString(c) doesn't always return in chunks of 8. That means you need to make sure your original output is all multiples of 8.
It'll end up looking something like this:
public String encrypt(String message) {
//Creates array of all the characters in the message we want to convert to binary
char[] characters = message.toCharArray();
String returnString = "";
String preProcessed = "";
for(int i = 0; i < characters.length; i++) {
//Converts the character to a binary string
preProcessed = Integer.toBinaryString((int)characters[i]);
//Adds enough zeros to the front of the string to make it a byte(length 8 bits)
String zerosToAdd = "";
if(preProcessed.length() < 8) {
for(int j = 0; j < (8 - preProcessed.length()); j++) {
zerosToAdd += "0";
}
}
returnString += zerosToAdd + preProcessed;
}
//Returns a string with a length that is a multiple of 8
return returnString;
}
//Converts a string message containing only 1s and 0s into ASCII plaintext
public String decrypt(String message) {
//Check to make sure that the message is all 1s and 0s.
for(int i = 0; i < message.length(); i++) {
if(message.charAt(i) != '1' && message.charAt(i) != '0') {
return null;
}
}
//If the message does not have a length that is a multiple of 8, we can't decrypt it
if(message.length() % 8 != 0) {
return null;
}
//Splits the string into 8 bit segments with spaces in between
String returnString = "";
String decrypt = "";
for(int i = 0; i < message.length() - 7; i += 8) {
decrypt += message.substring(i, i + 8) + " ";
}
//Creates a string array with bytes that represent each of the characters in the message
String[] bytes = decrypt.split(" ");
for(int i = 0; i < bytes.length; i++) {
/Decrypts each character and adds it to the string to get the original message
returnString += (char)Integer.parseInt(bytes[i], 2);
}
return returnString;
}