One thing to consider when you're converting your characters to binary to make sure you pad left with zeroes so the binary is 8 bits in length. This can be accomplished with something like this:
// "%08d" will pad zeroes to the left if it's not 8 in length
String.format("%08d", Integer.parseInt(Integer.toBinaryString((int)c)))
You're using a StringBuilder
to build the binary string, so you would use the above String.format()
like so:
String s = "ch";
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
sb.append(String.format("%08d", Integer.parseInt(Integer.toBinaryString((int)c))));
}
System.out.println(sb);
Results:
|--c---||--h---|
0110001101101000
And the reverse (binary to character) of it would be:
for (int i = 0; i < sb.length(); i += 8) {
System.out.print((char)Integer.parseInt(sb.substring(i, i + 8), 2));
}
System.out.println();
Results:
ch
All together would look like:
public static void main(String[] args) throws Exception {
String s = "ch";
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
sb.append(String.format("%08d", Integer.parseInt(Integer.toBinaryString((int)c))));
}
System.out.println(sb);
for (int i = 0; i < sb.length(); i += 8) {
System.out.print((char)Integer.parseInt(sb.substring(i, i + 8), 2));
}
System.out.println();
}
Results:
0110001101101000
ch