Java 中的二进制到文本
-
25-09-2019 - |
题
我有一个包含二进制数据的字符串(1110100),我想取出文本,以便可以打印它(1110100 将打印“t”)。我尝试过这个,它与我用来将文本转换为二进制的方法类似,但它根本不起作用:
public static String toText(String info)throws UnsupportedEncodingException{
byte[] encoded = info.getBytes();
String text = new String(encoded, "UTF-8");
System.out.println("print: "+text);
return text;
}
任何更正或建议将不胜感激。
谢谢!
解决方案
您可以使用 Integer.parseInt
以 2(二进制)为基数将二进制字符串转换为整数:
int charCode = Integer.parseInt(info, 2);
那么如果你想要对应的字符作为字符串:
String str = new Character((char)charCode).toString();
其他提示
我知道OP声明他们的二进制文件位于 String
格式,但为了完整起见,我想我会添加一个解决方案来直接从 byte[]
到字母字符串表示形式。
作为 卡萨布兰卡 表示您基本上需要获得字母字符的数字表示。如果您尝试转换任何比单个字符长的内容,它可能会作为 byte[]
而不是将其转换为字符串,然后使用 for 循环附加每个字符 byte
您可以使用 字节缓冲区 和 字符缓冲区 为您进行提升:
public static String bytesToAlphabeticString(byte[] bytes) {
CharBuffer cb = ByteBuffer.wrap(bytes).asCharBuffer();
return cb.toString();
}
注意:使用UTF字符集
或者使用 String 构造函数:
String text = new String(bytes, 0, bytes.length, "ASCII");
这是我的一个(关于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');
我相信有“更好”的方式来做到这一点,但这是最小的一个,你可能可以得到的。
下面是答案。
private String[] splitByNumber(String s, int size) {
return s.split("(?<=\\G.{"+size+"})");
}
周围的其他方法(其中,“信息”是输入文本和“s”的它的二进制版本)
byte[] bytes = info.getBytes();
BigInteger bi = new BigInteger(bytes);
String s = bi.toString(2);
看着那(这 parseInt
功能。您可能还需要演员阵容和 Character.toString
功能。
public static String binaryToText(String binary) {
return Arrays.stream(binary.split("(?<=\\G.{8})"))/* regex to split the bits array by 8*/
.parallel()
.map(eightBits -> (char)Integer.parseInt(eightBits, 2))
.collect(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append
).toString();
}
不隶属于 StackOverflow