Java中的字符串到二进制输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4173951/
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
String to binary output in Java
提问by Nick
I want to get binary (011001..) from a String but instead i get [B@addbf1 , there must be an easy transformation to do this but I don't see it.
我想从字符串中获取二进制 (011001..) 但我得到 [B@addbf1 ,必须有一个简单的转换才能做到这一点,但我没有看到。
public static String toBin(String info){
byte[] infoBin = null;
try {
infoBin = info.getBytes( "UTF-8" );
System.out.println("infoBin: "+infoBin);
}
catch (Exception e){
System.out.println(e.toString());
}
return infoBin.toString();
}
Here i get infoBin: [B@addbf1
and I would like infoBin: 01001...
在这里我得到 infoBin: [B@addbf1
我想要 infoBin: 01001 ...
Any help would be appreciated, thanks!
任何帮助将不胜感激,谢谢!
采纳答案by stacker
Only Integer has a method to convert to binary string representation check this out:
只有 Integer 有一个方法来转换为二进制字符串表示检查这个:
import java.io.UnsupportedEncodingException;
public class TestBin {
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] infoBin = null;
infoBin = "this is plain text".getBytes("UTF-8");
for (byte b : infoBin) {
System.out.println("c:" + (char) b + "-> "
+ Integer.toBinaryString(b));
}
}
}
would print:
会打印:
c:t-> 1110100
c:h-> 1101000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:p-> 1110000
c:l-> 1101100
c:a-> 1100001
c:i-> 1101001
c:n-> 1101110
c: -> 100000
c:t-> 1110100
c:e-> 1100101
c:x-> 1111000
c:t-> 1110100
Padding:
填充:
String bin = Integer.toBinaryString(b);
if ( bin.length() < 8 )
bin = "0" + bin;
回答by Thorbj?rn Ravn Andersen
When you try to use +
with an object in a string context the java compiler silently inserts a call to the toString() method.
当您尝试+
在字符串上下文中使用对象时,java 编译器会默默地插入对 toString() 方法的调用。
In other words your statements look like
换句话说,你的陈述看起来像
System.out.println("infobin: " + infoBin.toString())
System.out.println("infobin: " + infoBin.toString())
which in this case is the one inherited from Object.
在这种情况下,它是从 Object 继承的。
You will need to use a for-loop to pick out each byte from the byte array.
您将需要使用 for 循环从字节数组中挑选出每个字节。
回答by Andrzej Doyle
Arrays do not have a sensible toString
override, so they use the default object notation.
数组没有合理的toString
覆盖,因此它们使用默认的对象表示法。
Change your last line to
将最后一行更改为
return Arrays.toString(infoBin);
and you'll get the expected output.
你会得到预期的输出。