tags:

views:

92

answers:

2

How to represent the top 8 bytes of the MD5 hash of the bytes of the given String's UTF-8 encoding as a long in java?

+1  A: 
public static void main(final String[] args) throws Exception
{
    final MessageDigest md5 = MessageDigest.getInstance("MD5");
    final byte[] digest = md5.digest("Grommit".getBytes("UTF-8"));
    long result = 0;
    for (int i = 0; i < 8; i++)
    {
        System.out.println(Long.toHexString(0xFFL & digest[i]));
        result |= (0xFFL & digest[i]) << (i * 8);
    }
    System.out.println(Long.toHexString(result));
}
Jonathan Feinberg
+4  A: 

Try this:

MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] digest = md5.digest("Wallace".getBytes("UTF-8"));
long result = ByteBuffer.wrap(digest).getLong();
joeforker
Booya! Knowledge of the API trumps knowledge of bit twiddling. +1
Jonathan Feinberg