Last active
May 22, 2022 06:11
-
-
Save ikasoba/6bda5d1edfba614798def2a4c9bc39b5 to your computer and use it in GitHub Desktop.
base58 encoder and decoder for js
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
const base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" | |
const base58Table = {...Object.fromEntries(Object.entries(base58Chars).map(([k,v])=>[v,BigInt(k)])),...base58Chars} | |
/** @param {arrayBuffer} buf */ | |
function base58enc(buf){ | |
const u8 = new Uint8Array(buf) | |
let int = 0n | |
u8.forEach( (x,i) => int += BigInt(x * 256 ** (u8.length-1-i)) ) | |
let res = "" | |
while (1){ | |
const [x,y] = [int%58n,int/=58n] | |
res = base58Table[x] + res | |
if (!y)return res | |
} | |
} | |
/** @param {string} value */ | |
function base58dec(value){ | |
const u8 = [] | |
let int = 0n; | |
[...value].forEach( (x,i) => int += base58Table[x] * BigInt(58 ** (value.length-1-i)) ) | |
while (1){ | |
const [x,y] = [int%256n,int/=256n] | |
u8.unshift(Number(x)) | |
if (!y)return new Uint8Array(u8).buffer | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment