问题
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