为了账号安全,请及时绑定邮箱和手机立即绑定

Java中的二进制文本

Java中的二进制文本

长风秋雁 2019-10-21 12:52:29
我有一个带有二进制数据的字符串(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;    }任何更正或建议将不胜感激。
查看完整描述

3 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

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


int charCode = Integer.parseInt(info, 2);

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


String str = new Character((char)charCode).toString();


查看完整回答
反对 回复 2019-10-21
?
青春有我

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");


查看完整回答
反对 回复 2019-10-21
?
德玛西亚99

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');

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


查看完整回答
反对 回复 2019-10-21
  • 3 回答
  • 0 关注
  • 359 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信