Created
June 29, 2022 10:04
-
-
Save ikasoba/fefd5311ba8965caeaca426d57da86f8 to your computer and use it in GitHub Desktop.
任意進数のエンコード、デコード
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
class BaseN { | |
table = undefined | |
/** @type {bigint} */ | |
n = undefined | |
constructor(chars){ | |
this.table = new Map([...Object.entries(chars).map(([k,v])=>[v,BigInt(k)]),...Object.entries(chars).map(([k,v])=>[BigInt(k),v])]) | |
this.n = BigInt(chars.length) | |
} | |
/** @param {arrayBuffer} buf */ | |
enc(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%this.n,int/=this.n] | |
res = this.table.get(x) + res | |
if (!y)return res | |
} | |
} | |
/** @param {string} value */ | |
dec(value){ | |
const u8 = [] | |
let int = 0n; | |
[...value].forEach( (x,i) => int += this.table.get(x) * this.n ** BigInt(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