Created
September 13, 2016 15:06
-
-
Save bugventure/36cb8923ec212e47b47602e3821d1005 to your computer and use it in GitHub Desktop.
Base58 encode/decode a decimal number
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
var alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; | |
var base = alphabet.length; // base is the length of the alphabet (58 in this case) | |
// utility function to convert base 10 integer to base 58 string | |
function encode(num) { | |
var encoded = ''; | |
while (num){ | |
var remainder = num % base; | |
num = Math.floor(num / base); | |
encoded = alphabet[remainder].toString() + encoded; | |
} | |
return encoded; | |
} | |
// utility function to convert a base 58 string to base 10 integer | |
function decode(str) { | |
var decoded = 0; | |
while (str){ | |
var index = alphabet.indexOf(str[0]); | |
var power = str.length - 1; | |
decoded += index * (Math.pow(base, power)); | |
str = str.substring(1); | |
} | |
return decoded; | |
} | |
module.exports.encode = encode; | |
module.exports.decode = decode; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment