3 回答

TA贡献1824条经验 获得超5个赞
您可以使用Integer.parseInt基数2(二进制)将二进制字符串转换为整数:
int charCode = Integer.parseInt(info, 2);
然后,如果您希望将相应的字符作为字符串:
String str = new Character((char)charCode).toString();

TA贡献1784条经验 获得超8个赞
我知道OP指出他们的二进制文件采用某种String格式,但是出于完整性考虑,我想我将添加一个解决方案,以将a直接转换byte[]为字母String表示形式。
正如卡萨布兰卡所说,您基本上需要获得字母字符的数字表示形式。如果您尝试转换比单个字符长的任何内容,它可能会以a出现byte[],而不是将其转换为字符串,然后使用for循环将每个字符附加到字符之后,byte您可以使用ByteBuffer和CharBuffer为您进行提升:
public static String bytesToAlphabeticString(byte[] bytes) {
CharBuffer cb = ByteBuffer.wrap(bytes).asCharBuffer();
return cb.toString();
}
NB使用UTF字符集
或者使用String构造函数:
String text = new String(bytes, 0, bytes.length, "ASCII");

TA贡献1770条经验 获得超3个赞
这是我的(在Java 8上可以正常工作):
String input = "01110100"; // Binary input as String
StringBuilder sb = new StringBuilder(); // Some place to store the chars
Arrays.stream( // Create a Stream
input.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...
sb.append((char) Integer.parseInt(s, 2)) // ...and turn it into an int and then to a char
);
String output = sb.toString(); // Output text (t)
并将压缩方法打印到控制台:
Arrays.stream(input.split("(?<=\\G.{8})")).forEach(s -> System.out.print((char) Integer.parseInt(s, 2)));
System.out.print('\n');
我相信有“更好”的方法可以做到这一点,但这是您可能获得的最小方法。
添加回答
举报