Nic*_*ick 10 java string encoding string-conversion
我想从字符串中获取二进制(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();
}
Run Code Online (Sandbox Code Playgroud)
在这里我得到infoBin:[B @ addbf1
我希望infoBin:01001 ...
任何帮助将不胜感激,谢谢!
sta*_*ker 18
只有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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
会打印:
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
Run Code Online (Sandbox Code Playgroud)
填充:
String bin = Integer.toBinaryString(b);
if ( bin.length() < 8 )
bin = "0" + bin;
Run Code Online (Sandbox Code Playgroud)