Search code examples
javastring-formattingbinaryformatter

binary string with leading zeros issue


I have a string which is converted in binary format but the binary conversion method removes it leading zero's and I am not sure how much leading zero's I should add in the start .It depends on the string my code is as follows

public static void encodeString(String str){
        byte[] bytes=str.getBytes();
        String binary = new BigInteger(bytes).toString(2);

    }

Solution

  • I understand that you are trying to preserve the 8-bits representation of each character of your input String. to do so, I used this method:

        public static String byteFormat(String src) {
        StringBuilder sb = new StringBuilder();
    
        for (int i = 0; i < src.length(); i++) {
    
            char chr = src.charAt(i);
            String format= String.format("%8s", Integer.toBinaryString(chr)).replace(' ', '0');
            sb.append(format);
        }
        return sb.toString();
    
    }
    

    and I tested it like this :

    public static void main(String[] args) throws Exception {
    
        System.out.println(byteFormat("test"));
    }
    

    }

    it outputs :
    01110100011001010111001101110100