Java中的二进制文本

我有一个带有二进制数据的字符串(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;

    }

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


长风秋雁
浏览 360回答 3
3回答

沧海一幻觉

您可以使用Integer.parseInt基数2(二进制)将二进制字符串转换为整数:int charCode = Integer.parseInt(info, 2);然后,如果您希望将相应的字符作为字符串:String str = new Character((char)charCode).toString();

青春有我

我知道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");

德玛西亚99

这是我的(在Java 8上可以正常工作):String input = "01110100"; // Binary input as StringStringBuilder sb = new StringBuilder(); // Some place to store the charsArrays.stream( // Create a Stream&nbsp; &nbsp; 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...&nbsp; &nbsp; 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)));&nbsp;System.out.print('\n');我相信有“更好”的方法可以做到这一点,但这是您可能获得的最小方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java