3

I am working on a personal project. I want to create an encryption program that lets you encrypt, and decrypt a String using a key. Almost finished only need help with the final part. I want to convert a binary String into a text. Let's say the binary outcome(which I want to convert into a normal text) is:

01001000011000010110100001100001

This converted into text is "Haha".

NOTE: I am only working with BigIntegers since Almost every number I am using is too big for a normal Integer.

EDIT: Found the answer using this 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);
rr-
  • 14,303
  • 6
  • 45
  • 67
fihdi
  • 145
  • 1
  • 1
  • 12

1 Answers1

0

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"

It can probably be made prettier, but I didn't have an IDE handy (just thumbed it in on my phone).

You'll note that BigInteger isn't needed, and this code handles input of arbitrarily large length.

Bohemian
  • 412,405
  • 93
  • 575
  • 722