base32
This tag encodes and decodes base32
Created by: hackvertor
Installed 1 times
Category: Convert
Created on: Thursday, October 10, 2024 at 11:39:20 AM
Updated on: Thursday, October 10, 2024 at 11:39:20 AM
Tag arguments
[]
Code
class base32 {
encode(input) {
const base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let output = "";
let buffer = 0;
let bitsLeft = 0;
for (let i = 0; i < input.length; i++) {
buffer = (buffer << 8) | input.charCodeAt(i);
bitsLeft += 8;
while (bitsLeft >= 5) {
output += base32chars.charAt((buffer >> (bitsLeft - 5)) & 31);
bitsLeft -= 5;
}
}
if (bitsLeft > 0) {
output += base32chars.charAt((buffer << (5 - bitsLeft)) & 31);
}
return output.padEnd(Math.ceil(output.length / 8) * 8, "=");
}
decode(input) {
const base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
const cleanInput = input.replace(/=/g, "");
let buffer = 0;
let bitsLeft = 0;
let output = "";
for (let i = 0; i < cleanInput.length; i++) {
buffer = (buffer << 5) | base32chars.indexOf(cleanInput.charAt(i));
bitsLeft += 5;
if (bitsLeft >= 8) {
output += String.fromCharCode((buffer >> (bitsLeft - 8)) & 255);
bitsLeft -= 8;
}
}
return output;
}
matches(input) {
const base32Regex = /^[A-Z2-7]{10,}=*$/;
const result = base32Regex.exec(input);
if (result && result[0].length % 8 === 0) {
return result;
}
return null;
}
}