Skip to content

Instantly share code, notes, and snippets.

@geuis
Last active December 20, 2015 06:29
Show Gist options
  • Save geuis/6086349 to your computer and use it in GitHub Desktop.
Save geuis/6086349 to your computer and use it in GitHub Desktop.
Base32 decoder
(function(){
"use strict";
//Generate dictionary
var arr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.split(''),
dict = {};
for(var i=0, len=arr.length; i<arr.length; i++){
dict[arr[i]] = i;
}
var decode = function(hash){
var cache = 0,
count = 0,
bytes = [];
//remove placeholder chars
hash = hash.replace(/=/g,'');
var x = 0;
for(var i=0, len=hash.length; i<len; i++){
//add bits from val to cache
cache = (cache << 5) + dict[hash[i]];
count += 5;
if( count >= 8 ){
count -= 8;
//store decoded chaacter
bytes.push(cache >> count);
//remove used bits by masking agains unused bits
cache &= ((1 << count)-1);
}
}
return bytes;
}
//define as a global. Cheap way to make this work in a browser or node environment
var self = typeof window !== 'undefined'?
window:
GLOBAL;
self.base32decode = function(hash, handler){
var bytes = decode(hash);
//if the bytes need additional work, the user can specify a handler function that should return an array of the modified bytes
if( handler ){
bytes = handler(bytes);
}
//convert to text
for(var i=0; i<bytes.length; i++){
bytes[i] = String.fromCharCode(bytes[i]);
}
return bytes.join('');
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment