Thursday, August 11, 2011

Non-cryptographic hash function(UDF function) for mysql5.1

Some times, we want to use a hash funtion which is non-cryptographic,only create a number value,but mysql can't provide it, so I merge the "One At A Time hashing function" into mysql5.1,it  was originally created by Bob Jenkins.you can get my mysql hash function code from follow url:
http://forge.mysql.com/tools/tool.php?id=334

if you want use it in java and mysql,I modify the c code to java as following:

public static long hash32(String input) {
            try {
                  long hashend = 0L;
                  int hash = 0;
                  int hashbefore = 0;
                  long hashtemp = 0L;
                  for (byte bt : input.getBytes("utf-8")) {
                        hash += (bt & 0xFF);
                        hash += (hash << 10);
                        hash ^= (hash >>> 6);
                  }
                  hash += (hash << 3);
                  hash ^= (hash >>> 11);
                  hashbefore = hash;
                  hash += (hash << 15);
                  // finally result out rang of INT,
                  // so need long to save the data.
                  if (hash < 0) {
                        hashtemp = hashbefore << 15;
                        hashend = hashbefore + hashtemp;
                  } else
                        hashend = hash;
                  return hashend;
            } catch (Exception e) {
                  return 0;
            }
}

 following is java and mysql UDF testing result.

select hash32("A2ff7402d89c1086119bd7f17176ba66EEEEEEEEEEEEEEEEYYYYYYYY8888888888888888888888888888888888888888888888888888888") as hash32
+------------+
| hash32     |
+------------+
| 1143512335 |
+------------+

select hash32("1111111111111111111111111111111111111111") as hash32
+------------+
| hash32     |
+------------+
| 1867344944 |
+------------+

select hash32("aaabbbbbcccc1122228888888888888888888888") as hash32
+------------+
| hash32     |
+------------+
| 2697799865 |
+------------+

java:
hashvalue32=1143512335
hashvalue32=1867344944
hashvalue32=2697799865

No comments:

Post a Comment