Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

I'm working with some example java code for making md5 hashes. One part converts the results from bytes to a string of hex digits:

byte messageDigest[] = algorithm.digest();     

StringBuffer hexString = new StringBuffer();

for (int i=0;i<messageDigest.length;i++) {

    hexString.append(Integer.toHexString(0xFF & messageDigest[i]));

    }

However, it doesn't quite work since toHexString apparently drops off leading zeros. So, what's the simplest way to go from byte array to hex string that maintains the leading zeros?

1 Answer

0 votes
by (46k points)

A simple approach would be to check how many digits are output by Integer.toHexString() and add a leading zero to each byte if needed. Something like this:

public static String toHexString(byte[] bytes) {

    StringBuilder hexString = new StringBuilder();

    for (int i = 0; i < bytes.length; i++) {

        String hex = Integer.toHexString(0xFF & bytes[i]);

        if (hex.length() == 1) {

            hexString.append('0');

        }

        hexString.append(hex);

    }

    return hexString.toString();

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 14, 2019 in Java by Suresh (3.4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...