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;
}
任何更正或建议将不胜感激。
谢谢!
I have a String with binary data in it (1110100) I want to get the text out so I can print it (1110100 would print "t"). I tried this, it is similar to what I used to transform my text to binary but it's not working at all:
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;
}
Any corrections or suggestions would be much appreciated.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以使用
Integer.parseInt
以2(二进制)为基数将二进制字符串转换为整数:那么如果你想要对应的字符作为字符串:
You can use
Integer.parseInt
with a radix of 2 (binary) to convert the binary string to an integer:Then if you want the corresponding character as a string:
这是我的一个(在 Java 8 上工作正常):
以及打印到控制台的压缩方法:
我确信有“更好”的方法可以做到这一点,但这是您可能得到的最小的方法。
This is my one (Working fine on Java 8):
and the compressed method printing to console:
I am sure there are "better" ways to do this but this is the smallest one you can probably get.
我知道OP声明他们的二进制文件是
String
格式,但为了完整性,我想我会添加一个解决方案来直接从byte[]
转换为字母字符串表示形式。正如casablanca所说,你基本上需要获得字母字符的数字表示。如果您尝试转换任何长于单个字符的内容,它可能会以
byte[]
形式出现,而不是将其转换为字符串,然后使用 for 循环附加每个的字符>byte
您可以使用 ByteBuffer 和 CharBuffer 为您做提升:NB 使用 UTF 字符集
或者使用 String 构造函数:
I know the OP stated that their binary was in a
String
format but for the sake of completeness I thought I would add a solution to convert directly from abyte[]
to an alphabetic String representation.As casablanca stated you basically need to obtain the numerical representation of the alphabetic character. If you are trying to convert anything longer than a single character it will probably come as a
byte[]
and instead of converting that to a string and then using a for loop to append the characters of eachbyte
you can use ByteBuffer and CharBuffer to do the lifting for you:N.B. Uses UTF char set
Alternatively using the String constructor:
这就是答案。
Here is the answer.
相反(其中“info”是输入文本,“s”是它的二进制版本)
The other way around (Where "info" is the input text and "s" the binary version of it)
查看
parseInt
函数。您可能还需要强制转换和Character.toString
函数。Look at the
parseInt
function. You may also need a cast and theCharacter.toString
function.您也可以使用没有流和正则表达式的替代解决方案(基于卡萨布兰卡的答案):
您只需要附加指定的字符作为字符串到字符序列。
Also you can use alternative solution without streams and regular expressions (based on casablanca's answer):
you just need to append the specified character as a string to character sequence.