How to convert a string to a stream of bits in java

后端 未结 3 1992
感动是毒
感动是毒 2021-02-15 17:24

How to convert a string to a stream of bits zeroes and ones what i did i take a string then convert it to an array of char then i used method called forDigit(char,int) ,but it

相关标签:
3条回答
  • 2021-02-15 18:04
    String strToConvert = "abc";
    byte [] bytes = strToConvert.getBytes();
    StringBuilder bits = new StringBuilder(bytes.length * 8); 
    System.err.println(strToConvert + " contains " + bytes.length +" number of bytes");
    for(byte b:bytes) {
      bits.append(Integer.toString(b, 2));
    }   
    
    System.err.println(bits);
    char [] chars = new char[bits.length()];
    bits.getChars(0, bits.length(), chars, chars.length);
    
    0 讨论(0)
  • 2021-02-15 18:06

    I tried this one ..

    public String toBinaryString(String s) {
    
        char[] cArray=s.toCharArray();
    
        StringBuilder sb=new StringBuilder();
    
        for(char c:cArray)
        {
            String cBinaryString=Integer.toBinaryString((int)c);
            sb.append(cBinaryString);
        }
    
        return sb.toString();
    }
    
    0 讨论(0)
  • 2021-02-15 18:10

    Its easiest if you take two steps. String supports converting from String to/from byte[] and BigInteger can convert byte[] into binary text and back.

    String text = "Hello World!";
    System.out.println("Text: "+text);
    
    String binary = new BigInteger(text.getBytes()).toString(2);
    System.out.println("As binary: "+binary);
    
    String text2 = new String(new BigInteger(binary, 2).toByteArray());
    System.out.println("As text: "+text2);
    

    Prints

    Text: Hello World!
    As binary: 10010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001
    As text: Hello World!
    
    0 讨论(0)
提交回复
热议问题