二进制到Java中的文本

Nic*_*ick 7 java string encoding utf-8 nsstringencoding

我有一个包含二进制数据的字符串(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;
    }
Run Code Online (Sandbox Code Playgroud)

任何更正或建议将不胜感激.

谢谢!

cas*_*nca 27

您可以使用Integer.parseInt2的基数(二进制)将二进制字符串转换为整数:

int charCode = Integer.parseInt(info, 2);
Run Code Online (Sandbox Code Playgroud)

然后,如果您想将相应的字符作为字符串:

String str = new Character((char)charCode).toString();
Run Code Online (Sandbox Code Playgroud)

  • @Nick:把它投到`char`. (2认同)

小智 6

这是我的(在 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)
Run Code Online (Sandbox Code Playgroud)

以及打印到控制台的压缩方法:

Arrays.stream(input.split("(?<=\\G.{8})")).forEach(s -> System.out.print((char) Integer.parseInt(s, 2))); 
System.out.print('\n');
Run Code Online (Sandbox Code Playgroud)

我相信有“更好”的方法可以做到这一点,但这是你可能得到的最小的方法。


tar*_*rka 5

我知道 OP 声明他们的二进制文件是一种String格式,但为了完整起见,我想我会添加一个解决方案来直接从 abyte[]转换为字母字符串表示。

正如卡萨布兰卡所说,您基本上需要获得字母字符的数字表示。如果您尝试转换任何长度超过单个字符的内容,它可能会以 a 的形式出现byte[],而不是将其转换为字符串,然后使用 for 循环来附加每个字符,byte您可以使用ByteBufferCharBuffer为您完成提升:

public static String bytesToAlphabeticString(byte[] bytes) {
    CharBuffer cb = ByteBuffer.wrap(bytes).asCharBuffer();
    return cb.toString();
}
Run Code Online (Sandbox Code Playgroud)

NB 使用 UTF 字符集

或者使用 String 构造函数:

String text = new String(bytes, 0, bytes.length, "ASCII");
Run Code Online (Sandbox Code Playgroud)