带前导零的二进制字符串问题 [英] 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);
}
推荐答案
我了解您正在尝试保留输入 String
的每个字符的 8 位表示.为此,我使用了这种方法:
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();
}
我是这样测试的:
public static void main(String[] args) throws Exception {
System.out.println(byteFormat("test"));
}
}
它输出:01110100011001010111001101110100
这篇关于带前导零的二进制字符串问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文