binary string with leading zeros issue

筅森魡賤 提交于 2021-01-28 14:05:02

问题


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);

    }

回答1:


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




回答2:


The amount of leading zeroes would normally not matter, It's the same number anyways.

You can always left pad to the amount of zeroes you want manually



来源:https://stackoverflow.com/questions/46444872/binary-string-with-leading-zeros-issue

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