The select
SELECT CONVERT(BIGINT, HASHBYTES('MD5', 'http://stackoverflow.com'))
will yield the following result:
-3354682182756996262
If you now try to create a MD5 hash in C#
MD5 md5 = MD5.Create();
byte[] textToHash = Encoding.UTF8.GetBytes("http://stackoverflow.com");
byte[] result = md5.ComputeHash(textToHash);
long numeric = BitConverter.ToInt64(result, 0);
numeric
will be 8957512937738269783
.
So what's the issue (besides the fact that a MD5 hash is 128-bit and BIGINT
/long
is just 64-bit)?
It's an endian issue (the bytes are in the wrong order). Let's fix it using the BitConverter
class and reverse the bytes as needed:
MD5 md5 = MD5.Create();
byte[] textToHash = Encoding.UTF8.GetBytes("http://stackoverflow.com");
byte[] result = md5.ComputeHash(textToHash);
if (BitConverter.IsLittleEndian)
Array.Reverse(result);
long numeric = BitConverter.ToInt64(result, 0);
numeric
is now -3354682182756996262
as you want.