Skip to content

Instantly share code, notes, and snippets.

@amakukha
Last active July 27, 2021 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amakukha/e7a8fcf0c1ad0d1b76a26349c0d6ef24 to your computer and use it in GitHub Desktop.
Save amakukha/e7a8fcf0c1ad0d1b76a26349c0d6ef24 to your computer and use it in GitHub Desktop.
DJB2 hash in JavaScript (32-bit version)
<html>
<body>
<h2>32-bit DJB2 hash in JavaScript demo</h2>
<input type="file" id="file-input" />
<h3 id="result">Select file to calculate DJB2 hash</h3>
</body>
<script>
// DJB2 hash function. Takes ArrayBuffer
function hash_buf_djb2_32(buf) {
var hash = 5381;
let view = new Uint8Array(buf);
for (let num of view)
hash = ((hash << 5) + hash + num) & 0xFFFFFFFF;
return hash >>> 0;
}
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsArrayBuffer(file);
}
function displayContents(contents) {
var element = document.getElementById('result');
element.textContent = "Hash = " + hash_buf_djb2_32(contents) + ", Len = " + contents.byteLength;
}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
</script>
</html>
// 32-bit DJB2 hash in JavaScript
// DJB2 is probably the simplest among relatively good checksum and hash functions.
// DJB2 outperforms CRC32 in speed and comes close to it in performance.
// You should still use CRC32, especially if your CPU supports CRC calculation natively.
// On 32-bit or 64-bit architectures, MurmurHash can outperform DJB2.
// Takes ArrayBuffer
function hash_buf_djb2_32(buf) {
var hash = 5381;
let view = new Uint8Array(buf);
for (let num of view)
hash = ((hash << 5) + hash + num) & 0xFFFFFFFF;
return hash >>> 0;
}
// Takes string (NOTE: charCode can be larger than 255)
function hash_str_djb2_32(str) {
var len = str.length;
var hash = 5381;
for (var idx = 0; idx < len; ++idx) {
hash = ((hash << 5) + hash + str.charCodeAt(idx)) & 0xFFFFFFFF;
}
return hash >>> 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment