Skip to content

Instantly share code, notes, and snippets.

@davidglezz
Last active March 19, 2024 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidglezz/d948feede62fcb2fc5a9831abe1fdc1d to your computer and use it in GitHub Desktop.
Save davidglezz/d948feede62fcb2fc5a9831abe1fdc1d to your computer and use it in GitHub Desktop.
Basa256 encoder / decoder
// 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));
@davidglezz
Copy link
Author

davidglezz commented Mar 18, 2024

Comparison table for 1024bytes of binary data:

Chars File bytes
Not encoded 5120 5120
Base64 1366 1366 Until native Uint8Array.fromBase64() we need to implement a decoder like this
Base256 1024 2048 Simple decoder, Requires utf8 IDE.

const notEncoded = [ 127, 127, 168, 226, 120, 62, 44, 146, 82, ……, 213, 0, 30 ];
const base64data = 'f3+o4ng+LJJS……1YCA';
const base256dat = 'ĿĿŨƢĸþìŒĒ……ƕÀÞ';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment