I have an array of integer 1s and 0s (possibly need to get converted to byte
type?). I have used [an online ASCII to binary generator][1] to get the equivalent binary of this 6 digit letter sequence:
abcdef
should equal 011000010110001001100011011001000110010101100110
in binary.
My array is set up as int[] curCheckArr = new int[48];
and my string is basically just using a StringBuilder
to build the same ints as strings, and calling toString()
- so I have access to the code as a string or an array.
I have tried a few different methods, all of which crash the browser, including:
StringBuilder curCheckAlphaSB = new StringBuilder(); // Some place to store the chars
Arrays.stream( // Create a Stream
curCheckString.split("(?<=\\G.{8})") // Splits the input string into 8-char-sections (Since a char has 8 bits = 1 byte)
).forEach(s -> // Go through each 8-char-section...
curCheckAlphaSB.append((char) Integer.parseInt(s, 2)) // ...and turn it into an int and then to a char
);
String curAlpha = curCheckAlphaSB.toString();
and
String curAlpha = "";
for (int b = 0; b < curCheckString.length()/8; b++) {
int a = Integer.parseInt(curAlpha.substring(8*b,(b+1)*8),2);
curAlpha += (char)(a);
}
How can I most efficiently convert these 48 1s and 0s to a six digit alpha character sequence?
Assuming each character is represented by precisely one byte
you can iterate over the input with Integer.parseInt()
(because byte
value in the input is potentially unsigned):
String input = "011000010110001001100011011001000110010101100110";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i += 8) {
int c = Integer.parseInt(input.substring(i, i + 8), 2);
sb.append((char) c);
}
System.out.println(sb); // abcdef