Skip to content

Instantly share code, notes, and snippets.

@cvzi
Forked from stubbetje/base64.js
Last active October 24, 2019 11:52
Show Gist options
  • Save cvzi/5052dd21f13862356c7606a87dd43865 to your computer and use it in GitHub Desktop.
Save cvzi/5052dd21f13862356c7606a87dd43865 to your computer and use it in GitHub Desktop.
Base64 encode in javascript
function base64encode (s) {
// from https://gist.github.com/stubbetje/229984
const base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('')
const l = s.length
let o = ''
for (let i = 0; i < l; i++) {
const byte0 = s.charCodeAt(i++) & 0xff
const byte1 = s.charCodeAt(i++) & 0xff
const byte2 = s.charCodeAt(i) & 0xff
o += base64[byte0 >> 2]
o += base64[((byte0 & 0x3) << 4) | (byte1 >> 4)]
const t = i - l
if (t >= 0) {
if (t === 0) {
o += base64[((byte1 & 0x0f) << 2) | (byte2 >> 6)]
o += base64[64]
} else {
o += base64[64]
o += base64[64]
}
} else {
o += base64[((byte1 & 0x0f) << 2) | (byte2 >> 6)]
o += base64[byte2 & 0x3f]
}
}
return o
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment