Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

java - BigInteger.toString method is deleting leading 0

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

This returns not 32 character string but a 31 character string 8611c0b0832bce5a19ceee626a403a7

Expected String is 08611c0b0832bce5a19ceee626a403a7

Leading 0 is missing in the output.

I tried the other method

byte[] md5sum = digest.digest();
output = new String(Hex.encodeHex(md5sum));

And the output is as expected.

I checked the doc and Integer.toString does the conversion according to it

The digit-to-character mapping provided by Character.forDigit is used, and a minus sign is prepended if appropriate.

and in Character.forDigit methos

The digit argument is valid if 0 <=digit < radix.

Can some one tell me how two methods are different and why leading 0 is deleted?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...