Skip to content

Instantly share code, notes, and snippets.

@creaktive
Created January 30, 2025 20:30
Show Gist options
  • Save creaktive/4f28f01318b25b87fab1ab1d23caebd8 to your computer and use it in GitHub Desktop.
Save creaktive/4f28f01318b25b87fab1ab1d23caebd8 to your computer and use it in GitHub Desktop.
Base32 in pure JavaScript
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
function encodeBase32(input) {
const buffer = Buffer.from(input);
let bits = 0;
let value = 0;
let output = '';
for (let i = 0; i < buffer.length; i++) {
value = (value << 8) | buffer[i];
bits += 8;
while (bits >= 5) {
output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) {
output += BASE32_ALPHABET[(value << (5 - bits)) & 31];
}
while (output.length % 8) {
output += '=';
}
return output;
}
const encoded = encodeBase32('Hello');
// JBSWY3DP
console.log(encoded);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment