BigInteger.toString方法正在删除前导0 [英] BigInteger.toString method is deleting leading 0
问题描述
我正在尝试使用MessageDigest生成MD5总和。
我正在使用以下代码。
I am trying to generate MD5 sum using MessageDigest. And i am having following code.
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
output = bigInt.toString(16);
这不返回32个字符串,而是31个字符的字符串 8611c0b0832bce5a19ceee626a403a7
This returns not 32 character string but a 31 character string 8611c0b0832bce5a19ceee626a403a7
预期字符串 08611c0b0832bce5a19ceee626a403a7
输出中缺少前导0。
我尝试了其他方法
byte[] md5sum = digest.digest();
output = new String(Hex.encodeHex(md5sum));
输出是预期的。
我检查了doc并且Integer.toString根据它进行了转换
I checked the doc and Integer.toString does the conversion according to it
Character.forDigit提供的数字到字符映射是使用
,如果合适,前缀为减号。
The digit-to-character mapping provided by Character.forDigit is used, and a minus sign is prepended if appropriate.
和Character.forDigit方法
and in Character.forDigit methos
如果0< = digit< 0,则数字参数有效radix。
The digit argument is valid if 0 <=digit < radix.
有人可以告诉我两种方法有何不同以及为什么前导0被删除?
Can some one tell me how two methods are different and why leading 0 is deleted?
推荐答案
我个人避免使用 BigInteger
将二进制数据转换为文本。这并不是它的真正含义,即使可以用于此目的。有大量代码可用于将 byte []
转换为其十六进制表示 - 例如使用 Apache Commons Codec 或简单的单一方法:
I would personally avoid using BigInteger
to convert binary data to text. That's not really what it's there for, even if it can be used for that. There's loads of code available to convert a byte[]
to its hex representation - e.g. using Apache Commons Codec or a simple single method:
private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
public static String toHex(byte[] data) {
char[] chars = new char[data.length * 2];
for (int i = 0; i < data.length; i++) {
chars[i * 2] = HEX_DIGITS[(data[i] >> 4) & 0xf];
chars[i * 2 + 1] = HEX_DIGITS[data[i] & 0xf];
}
return new String(chars);
}
这篇关于BigInteger.toString方法正在删除前导0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!