String to binary output in Java
•
Java
I want to get binary (011001..) from a string, But I get [b @ addbf1, there must be a simple conversion, but I can't see it
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 I want infobin: 01001
Any help will be appreciated, thank you!
Solution
Only integers have a way to convert to binary string representation to check this:
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)); } } }
Will 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
fill:
String bin = Integer.toBinaryString(b); if ( bin.length() < 8 ) bin = "0" + bin;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码