Skip to content

Instantly share code, notes, and snippets.

@qubyte
Created November 15, 2021 09:59
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 qubyte/420ee02c94289d4402f723b9a063ee0e to your computer and use it in GitHub Desktop.
Save qubyte/420ee02c94289d4402f723b9a063ee0e to your computer and use it in GitHub Desktop.
Convert a Uint8Array to base64.
/**
* There's no real reason to use this. Buffer is available in node:
*
* Buffer.from(typedArray.buffer).toString('base64');
*
* and the browser has atob/btoa (which are fine to use for the ascii
* characters used to represent bytes.
*/
function byteToBin(byte) {
return [
byte & 128 && 1,
byte & 64 && 1,
byte & 32 && 1,
byte & 16 && 1,
byte & 8 && 1,
byte & 4 && 1,
byte & 2 && 1,
byte & 1 && 1
].join('');
}
const base64Table = new Map([
['000000', 'A'], ['010000', 'Q'], ['100000', 'g'], ['110000', 'w'],
['000001', 'B'], ['010001', 'R'], ['100001', 'h'], ['110001', 'x'],
['000010', 'C'], ['010010', 'S'], ['100010', 'i'], ['110010', 'y'],
['000011', 'D'], ['010011', 'T'], ['100011', 'j'], ['110011', 'z'],
['000100', 'E'], ['010100', 'U'], ['100100', 'k'], ['110100', '0'],
['000101', 'F'], ['010101', 'V'], ['100101', 'l'], ['110101', '1'],
['000110', 'G'], ['010110', 'W'], ['100110', 'm'], ['110110', '2'],
['000111', 'H'], ['010111', 'X'], ['100111', 'n'], ['110111', '3'],
['001000', 'I'], ['011000', 'Y'], ['101000', 'o'], ['111000', '4'],
['001001', 'J'], ['011001', 'Z'], ['101001', 'p'], ['111001', '5'],
['001010', 'K'], ['011010', 'a'], ['101010', 'q'], ['111010', '6'],
['001011', 'L'], ['011011', 'b'], ['101011', 'r'], ['111011', '7'],
['001100', 'M'], ['011100', 'c'], ['101100', 's'], ['111100', '8'],
['001101', 'N'], ['011101', 'd'], ['101101', 't'], ['111101', '9'],
['001110', 'O'], ['011110', 'e'], ['101110', 'u'], ['111110', '+'],
['001111', 'P'], ['011111', 'f'], ['101111', 'v'], ['111111', '/']
]);
export default function toBase64() {
// This is certainly not the best way to do this, but it works well enough
// and is reasonably simple to understand.
const binaryString = Array.from(this, byteToBin).join('');
let base64 = '';
for (let offset = 0; offset < binaryString.length; offset += 6) {
base64 += base64Table.get(binaryString.slice(offset, offset + 6).padEnd(6, '0'));
}
const padding = Array(base64.length % 4)
.fill('=')
.join('');
return base64 + padding;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment