Created
May 2, 2012 13:36
-
-
Save icoloma/2576554 to your computer and use it in GitHub Desktop.
JavaScript implementation of Base58
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
This is a javascript port of the Base58 code present at | |
http://icoloma.blogspot.com.es/2010/03/create-your-own-bitly-using-base58.html | |
*/ | |
var Base58 = (function() { | |
var | |
BASE58_CHARS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; | |
return { | |
numberToAlpha: function(number) { | |
var buffer = ''; | |
do { | |
buffer = buffer + BASE58_CHARS[number % BASE58_CHARS.length]; | |
number = (number / BASE58_CHARS.length) >> 0; | |
} while (number > 0); | |
return buffer; | |
}, | |
alphaToNumber: function(chars) { | |
var result = 0, multiplier = 1, index = 0; | |
for (; index < chars.length; index++) { | |
var c = chars[index]; | |
var digit; | |
if (c >= '1' && c <= '9') { | |
digit = c - '1'; | |
} else if (c >= 'A' && c < 'I') { | |
digit = (c - 'A') + 9; | |
} else if (c > 'I' && c < 'O') { | |
digit = (c - 'J') + 17; | |
} else if (c > 'O' && c <= 'Z') { | |
digit = (c - 'P') + 22; | |
} else if (c >= 'a' && c < 'l') { | |
digit = (c - 'a') + 33; | |
} else if (c > 'l' && c <= 'z') { | |
digit = (c - 'l') + 43; | |
} else { | |
throw new Error("Illegal character found: '" + c + "'"); | |
} | |
result += digit * multiplier; | |
multiplier = multiplier * BASE58_CHARS.length; | |
} | |
return result; | |
} | |
}; | |
})(); | |
// Uncomment one of these to use as bookmarklet | |
alert("The equivalent number is: " + Base58.alphaToNumber(prompt("Introduce a Base58 text"))); | |
alert("The Base58 conversion is: " + Base58.numberToAlpha(prompt("Introduce a number", 0))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment