| 24 | * toBase64("Hello"); |
| 25 | */ |
| 26 | export function toBase64(data, alphabet="A-Za-z0-9+/=") { |
| 27 | if (!data) return ""; |
| 28 | if (typeof data == "string") { |
| 29 | data = Utils.strToArrayBuffer(data); |
| 30 | } |
| 31 | if (data instanceof ArrayBuffer) { |
| 32 | data = new Uint8Array(data); |
| 33 | } |
| 34 | |
| 35 | alphabet = Utils.expandAlphRange(alphabet).join(""); |
| 36 | if (alphabet.length !== 64 && alphabet.length !== 65) { // Allow for padding |
| 37 | throw new OperationError(`Invalid Base64 alphabet length (${alphabet.length}): ${alphabet}`); |
| 38 | } |
| 39 | |
| 40 | let output = "", |
| 41 | chr1, chr2, chr3, |
| 42 | enc1, enc2, enc3, enc4, |
| 43 | i = 0; |
| 44 | |
| 45 | while (i < data.length) { |
| 46 | chr1 = data[i++]; |
| 47 | chr2 = data[i++]; |
| 48 | chr3 = data[i++]; |
| 49 | |
| 50 | enc1 = chr1 >> 2; |
| 51 | enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); |
| 52 | enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); |
| 53 | enc4 = chr3 & 63; |
| 54 | |
| 55 | if (isNaN(chr2)) { |
| 56 | enc3 = enc4 = 64; |
| 57 | } else if (isNaN(chr3)) { |
| 58 | enc4 = 64; |
| 59 | } |
| 60 | |
| 61 | output += alphabet.charAt(enc1) + alphabet.charAt(enc2) + |
| 62 | alphabet.charAt(enc3) + alphabet.charAt(enc4); |
| 63 | } |
| 64 | |
| 65 | return output; |
| 66 | } |
| 67 | |
| 68 | |
| 69 | /** |