-
-
Save cvzi/5052dd21f13862356c7606a87dd43865 to your computer and use it in GitHub Desktop.
Base64 encode in javascript
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 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