DJB2 String Hashing Algorithm Implemented in Erlang Wed, 29 Jul 2009 15:53:45 -0400

Erlang is a very interesting functional programming language that has been receiving a fair amount of attention lately. So I've been playing with it off and on as my little fun project for educating myself. So to give back here is a simple DJB2 hashing algorithm implemented in Erlang.

Something I have had problems with before when implementing DJB2 in those languages (such as Python) is the native infinite precision integers of those languages. However by bitwise AND logic the result of the hash against the maximum value of a C unsigned long negates that by truncating the result buffer so we remain using the proper number of bits for the hashing.


-module(djb2).
-author('Brian Smith http://www.modernninja.com/').
-export([hash/1, djb2/2]).

-define(INIT_HASH, 5381).

hash(String) -> djb2(String, ?INIT_HASH).

djb2([], Hash) -> Hash;
djb2([Head|Rest], Hash) -> djb2(Rest, (((Hash bsl 5) + Hash) + Head) band 16#FFFFFFFF).


Comments:

  TSwain Sun, 7 Feb 2010 10:11:37 -0500
There is obviously a lot to learn. There are some good points here.
  Reseller Hosting Mon, 11 Jan 2010 07:25:22 -0500
Your blog keeps getting better and better! Your older articles are not as good as newer ones you have a lot more creativity and originality now keep it up!
  Sam fisher Sat, 28 Nov 2009 06:54:13 -0500
Enjoyed reading through this site, I will send this site to a few of my friends
  Robert Virding Tue, 4 Aug 2009 00:30:35 -0400
It would be a little clearer to use 16#FFFFFFFF instead of 4294967295.
  Brian Tue, 4 Aug 2009 12:21:53 -0400
your absolutely right, it was my haste i suppose.
  Kelli Garner Thu, 1 Oct 2009 08:08:24 -0400
I enjoy this site, it is worth me coming back
  Car Insurance Guy Wed, 11 Nov 2009 10:16:01 -0500
Ah!!! at last I found what I was looking for. Somtimes it takes so much effort to find even tiny useful piece of information. Nice post. Thanks
  Brian Tue, 11 Aug 2009 16:00:13 -0400
I have updated as mentioned, thanks for the tip Robert I appreciate it
  witek Wed, 12 Aug 2009 10:12:14 -0400
Sorry but djb2 isn't very good or very fast. this is pointeless to implement it in erlang, if performance will be very small. Use erlang:phash/2, or write BIF for djb2's hash. or better something like lookup3 or Mrumrumur, which are extreamly fast and have good statistical properties.
  Brian Wed, 12 Aug 2009 10:16:06 -0400
@witek I am unfamiliar with those, I've only started working with erlang this past week or so, so I am learning. DJB2 is a fairly fast and well balanced hash for small blocks of data. For my purposes my hashes are rarely longer than 30 bytes.

Post Comment

  • Disclaimer
  • The ideas and opinions expressed here are mine.
  • I'm a Linux and BSD user, and lean heavily toward the use of OSS vs certain other commercial solutions.

View the Ninja's profile on LinkedIn

:= RSS =: