我有一个整数1和0的数组(可能需要转换为byte
类型?)。我使用[在线ASCII到二进制生成器] [1]来获得这个6位字母序列的等效二进制:
abcdef
应该等于011000010110001001100011011001000110010101100110
二进制。
我的数组设置为int[] curCheckArr = new int[48];
,我的字符串基本上只是使用StringBuilder
来构建与字符串相同的整数,并调用toString()
- 所以我可以访问代码作为字符串或数组。
我尝试了一些不同的方法,所有这些方法都会使浏览器崩溃,包括:
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();
和
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);
}
如何才能最有效地将这些48 1和0转换为6位字母字符序列?
假设每个字符由恰好一个byte
表示,您可以使用Integer.parseInt()
迭代输入(因为输入中的byte
值可能是无符号的):
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
使用正则表达式可能是这些中最慢的部分。使用预编译的正则表达式会有所帮助,但子字符串更快。不创建任何字符串,除了结果会更快。例如使用StringBuilder而不是+=
for String。