How do I turn a binary string into text?
I am working on a personal project. I want to create an encryption program that allows you to encrypt and decrypt a string using a key. The help is almost finished with only the final part. I want to convert a binary string to text. Let's say the binary result (which I want to convert to plain text):
01001000011000010110100001100001
This is converted to the text "Haha".
NOTE. I only work with BigIntegers as almost every number I use is too large for a regular Integer.
EDIT: Found an answer using this code:
StringBuffer output = new StringBuffer();
for (int i = 0;i < input.length();i += 8) {
output.append((char) Integer.parseInt(input.substring(i, i + 8), 2));
}
System.out.println(output);
+3
source to share
1 answer
This code will do it in one line:
String str = "01001000011000010110100001100001";
String decoded = Arrays.stream(str.split("(?<=\\G.{8})"))
.map(s -> Integer.parseInt(s, 2))
.map(i -> "" + Character.valueOf((char)i.intValue()))
.collect(Collectors.joining("")); // "Haha"
Most likely it could be made prettier, but I didn't have an IDE (I just had it on it).
You will notice that it is BigInteger
not required, and this code handles any length of input.
0
source to share