How to convert a binary representation of a string into byte in Java?

后端 未结 3 1999
名媛妹妹
名媛妹妹 2021-01-20 17:11

as the title says, how do I do it? Its easy to convert from string -> byte -> string binary, But how do I convert back? Below is a example. The output is : \'f\' to binary:

3条回答
  •  粉色の甜心
    2021-01-20 17:42

    I made like this, converted a string s -> byte[] and then used Integer.toBinaryString to get binaryStringRep. I converted bianryStringRep by using Byte.parseByte to get the bianryStringRep into byte and the String(newByte[]) to get the byte[] into a String! Hope it helps others then me aswell! ^^

    public class main{
        public static void main(String[] args) throws UnsupportedEncodingException {
    
             String s = "foo";
              byte[] bytes = s.getBytes();
              byte[] newBytes = new byte[s.getBytes().length];
              for(int i = 0; i < bytes.length; i++){
                  String binaryStringRep = String.format("%8s", Integer.toBinaryString(bytes[i] & 0xFF)).replace(' ', '0');
                  byte newByte = Byte.parseByte(binaryStringRep, 2);
                  newBytes[i] = newByte;
              }
    
            String str = new String(newBytes, "UTF-8");
            System.out.println(str);
        }
    }
    

提交回复
热议问题