Last active
September 18, 2022 08:39
-
-
Save meirkl/5a472ab48cbe478c735f7b2b99238220 to your computer and use it in GitHub Desktop.
This file contains 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
function Base32(v) { | |
v = v?.toString(); | |
if (!v || !v.length) { | |
throw new Error('Value must not be empty'); | |
} | |
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; | |
let bits = 0; | |
let value = 0; | |
let base32 = ''; | |
const data = Buffer.from(v); | |
for (let i = 0; i < data.length; i++) { | |
value = (value << 8) | data[i]; | |
bits += 8; | |
while (bits >= 5) { | |
base32 += alphabet[(value >>> (bits - 5)) & 31]; | |
bits -= 5; | |
} | |
} | |
if (bits > 0) { | |
base32 += alphabet[(value << (5 - bits)) & 31]; | |
} | |
while (base32.length % 8 !== 0) { | |
base32 += '='; | |
} | |
return base32; | |
} | |
console.log(Base32('test')); |
This file contains 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
function Base32(v) { | |
v = v?.toString(); | |
if (!v || !v.length) { | |
throw new Error('Value must not be empty'); | |
} | |
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; | |
const binaryArray = Array.from(v).map((c) => { | |
const ascii = c.charCodeAt(0); | |
let binary = ascii.toString(2); | |
binary = '0'.repeat(8).substring(binary.length) + binary; | |
return binary; | |
}); | |
while (binaryArray.length % 5) { | |
binaryArray.push('x'.repeat(8)); | |
} | |
const groups = binaryArray.join('').match(/.{1,5}/g); | |
const base32 = groups | |
.map((g) => { | |
if (g === 'x'.repeat(5)) { | |
return '='; | |
} | |
const index = parseInt(g.replace(/x/g, '0'), 2); | |
return alphabet[index]; | |
}) | |
.join(''); | |
return base32; | |
} | |
console.log(Base32('test')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment