Created
January 30, 2025 20:30
-
-
Save creaktive/4f28f01318b25b87fab1ab1d23caebd8 to your computer and use it in GitHub Desktop.
Base32 in pure JavaScript
This file contains hidden or 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
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