Java中的二进制到文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4211705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binary to text in Java
提问by Nick
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:
我有一个包含二进制数据的字符串 (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;
}
Any corrections or suggestions would be much appreciated.
任何更正或建议将不胜感激。
Thanks!
谢谢!
采纳答案by casablanca
You can use Integer.parseInt
with a radix of 2 (binary) to convert the binary string to an integer:
您可以使用Integer.parseInt
基数为 2(二进制)将二进制字符串转换为整数:
int charCode = Integer.parseInt(info, 2);
Then if you want the corresponding character as a string:
然后如果你想将相应的字符作为字符串:
String str = new Character((char)charCode).toString();
回答by Matthew Flaschen
Look at the parseInt
function. You may also need a cast and the Character.toString
function.
看parseInt
功能。您可能还需要演员表和Character.toString
函数。
回答by Emil
The other way around (Where "info" is the input text and "s" the binary version of it)
另一种方式(其中“信息”是输入文本,“s”是它的二进制版本)
byte[] bytes = info.getBytes();
BigInteger bi = new BigInteger(bytes);
String s = bi.toString(2);
回答by Nelson Poon
Here is the answer.
这是答案。
private String[] splitByNumber(String s, int size) {
return s.split("(?<=\G.{"+size+"})");
}
回答by tarka
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 a byte[]
to an alphabetic String representation.
我知道 OP 声明他们的二进制文件是一种String
格式,但为了完整起见,我想我会添加一个解决方案来直接从 abyte[]
转换为字母字符串表示。
As casablancastated 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 each byte
you can use ByteBufferand CharBufferto do the lifting for you:
正如卡萨布兰卡所说,您基本上需要获得字母字符的数字表示。如果您尝试转换任何比单个字符长的内容,它可能会以 a 的形式出现byte[]
,而不是将其转换为字符串,然后使用 for 循环来附加每个字符,byte
您可以使用ByteBuffer和CharBuffer为您完成提升:
public static String bytesToAlphabeticString(byte[] bytes) {
CharBuffer cb = ByteBuffer.wrap(bytes).asCharBuffer();
return cb.toString();
}
N.B. Uses UTF char set
NB 使用 UTF 字符集
Alternatively using the String constructor:
或者使用 String 构造函数:
String text = new String(bytes, 0, bytes.length, "ASCII");
回答by Leon Kasko
This is my one (Working fine on Java 8):
这是我的(在 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)
and the compressed method printing to console:
以及打印到控制台的压缩方法:
Arrays.stream(input.split("(?<=\G.{8})")).forEach(s -> System.out.print((char) Integer.parseInt(s, 2)));
System.out.print('\n');
I am sure there are "better" ways to do this but this is the smallest one you can probably get.
我相信有“更好”的方法可以做到这一点,但这是你可能得到的最小的方法。
回答by Maroine Mlis
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();
}
回答by invzbl3
Also you can use alternative solution without streams and regular expressions (based on casablanca's answer):
您也可以使用没有流和正则表达式的替代解决方案(基于卡萨布兰卡的回答):
public static String binaryToText(String binaryString) {
StringBuilder stringBuilder = new StringBuilder();
int charCode;
for (int i = 0; i < binaryString.length(); i += 8) {
charCode = Integer.parseInt(binaryString.substring(i, i + 8), 2);
String returnChar = Character.toString((char) charCode);
stringBuilder.append(returnChar);
}
return stringBuilder.toString();
}
you just need to appendthe specified character as a string to character sequence.
您只需要将指定的字符作为字符串附加到字符序列。