Last active
March 19, 2024 22:32
-
-
Save davidglezz/d948feede62fcb2fc5a9831abe1fdc1d to your computer and use it in GitHub Desktop.
Basa256 encoder / decoder
This file contains 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
// A simple way to store binary data inside a js/ts file with a density of 1 char per byte. | |
// Even though each char takes 2 bytes. | |
const b256enc = (buff: Uint8Array) => [...buff].map(i => String.fromCodePoint(i + 192)).join(''); | |
const b256dec = (str: string) => str.split('').map(c => c.charCodeAt(0) - 192); | |
// Example 1: Basic usage | |
const data = new Uint8Array([ 127, 127, 168, 226, 120, 62, 44, 146, 82, 213, 0, 30 ]); | |
const encoded = b256enc(data); | |
console.log(encoded); // 'ĿĿŨƢĸþìŒĒƕÀÞ' | |
const decoded = b256dec(encoded); | |
console.log(decoded); // (12) [127, 127, 168, 226, 120, 62, 44, 146, 82, 213, 0, 30] | |
// Example 2 - Inline 4kb data | |
// Before: 5 chars per byte | |
const data = new Uint8Array([ 127, 127, 168, 226, 120, '...more data...', 62, 44, 146, 82, 213, 0, 30 ]); | |
// After: 1 char per byte | |
const data = new Uint8Array('ĿĿŨƢĸþ...more data...ìŒĒƕÀÞ'.split('').map(c => c.charCodeAt(0) - 192)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comparison table for 1024bytes of binary data: