我想从字符串中获取二进制文件 (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();
}
在这里我得到 infoBin:[B@addbf1
我想要 infoBin: 01001...
任何帮助将不胜感激,谢谢!
最佳答案
只有 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));
}
}
}
将打印:
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
填充:
String bin = Integer.toBinaryString(b);
if ( bin.length() < 8 )
bin = "0" + bin;
关于java - 字符串到Java中的二进制输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4173951/