I had an interview recently and discovered that I'd forgotten some of the basics. I've been playing around again and have written a function that will take a binary string (there is no validation yet) and returns the ascii representation of said string.
I'm looking for advice or tips on how it could be improved. I don't want to use any of the API functions, this is more of a playground scenario in which I might be able to learn something.
Thanks for any help.
Sample output:
01101000 01100101 01101100 01101100 01101111
104
101
108
108
111
hello
public static String convertBinaryStringToString(String string){
StringBuilder sb = new StringBuilder();
char[] chars = string.replaceAll("\\s", "").toCharArray();
int [] mapping = {1,2,4,8,16,32,64,128};
for (int j = 0; j < chars.length; j+=8) {
int idx = 0;
int sum = 0;
for (int i = 7; i>= 0; i--) {
if (chars[i+j] == '1') {
sum += mapping[idx];
}
idx++;
}
System.out.println(sum);//debug
sb.append(Character.toChars(sum));
}
return sb.toString();
}