Fix base64 encoding

Fixes #9.
This commit is contained in:
Florine W. Dekker 2020-04-05 13:03:44 +02:00
parent 14369ab169
commit 353937e3a1
Signed by: FWDekker
GPG Key ID: B1B567AF58D6EE0F
1 changed files with 28 additions and 2 deletions

View File

@ -55,7 +55,7 @@
<a href="https://git.fwdekker.com/FWDekker/converter/src/branch/master/LICENSE">MIT License</a>.
Source code available on <a href="https://git.fwdekker.com/FWDekker/converter/">git</a>.
<div style="float: right;">v1.4.3</div>
<div style="float: right;">v1.4.4</div>
</section>
</footer>
</main>
@ -132,6 +132,32 @@
}
}
class Base64NumeralSystem extends NumeralSystem {
constructor(alphabet) {
super(64, alphabet, true);
}
decimalToBase(decimalNumber) {
const hex = decimalNumber.toString(16);
const b64 = Array.from(hex.padStart(hex.length + hex.length % 2))
.reduce((result, value, index, array) => {
if (index % 2 === 0) result.push(array.slice(index, index + 2));
return result;
}, [])
.map(pair => String.fromCharCode(parseInt(pair.join(""), 16)))
.join("");
return btoa(b64);
}
baseToDecimal(baseString) {
const hex = Array.from(atob(baseString))
.map(char => char.charCodeAt(0).toString(16).padStart(2, "0")).join("");
return bigInt(hex, 16);
}
}
class Base64NumeralSystemInput extends NumeralSystemInput {
// TODO Convert static methods to static properties once supported by Firefox
static defaultAlphabet() {
@ -144,7 +170,7 @@
constructor(name) {
super(name, new NumeralSystem(64, Base64NumeralSystemInput.defaultAlphabet(), true));
super(name, new Base64NumeralSystem(Base64NumeralSystemInput.defaultAlphabet()));
this.dropdownLabel = document.createElement("label");
this.dropdownLabel.setAttribute("for", `${this.name}Dropdown`);