String to binary output in Java

强颜欢笑 提交于 2019-11-30 08:58:21

Only Integer has a method to convert to binary string representation check this out:

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;

Arrays do not have a sensible toString override, so they use the default object notation.

Change your last line to

return Arrays.toString(infoBin);

and you'll get the expected output.

When you try to use + with an object in a string context the java compiler silently inserts a call to the toString() method.

In other words your statements look like

System.out.println("infobin: " + infoBin.toString())

which in this case is the one inherited from Object.

You will need to use a for-loop to pick out each byte from the byte array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!