Skip to content

Commit 198229b

Browse files
author
Nicholas C. Zakas
committed
Updated base64encode() with simpler implementation
1 parent 78d25e4 commit 198229b

File tree

1 file changed

+33
-50
lines changed

1 file changed

+33
-50
lines changed

encodings/base64/base64.js

Lines changed: 33 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -56,66 +56,49 @@ function padRight(bits, length){
5656
* @return {String} The base64-encoded string.
5757
*/
5858
function base64Encode(text){
59-
60-
//local variables
61-
var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
62-
part, index,
63-
i=0, j=0,
64-
padding="",
65-
quantaCount,
66-
bits = [],
67-
result = [];
6859

69-
//verify that there are no characters out of range
7060
if (/([^\u0000-\u00ff])/.test(text)){
7161
throw new Error("Can't base64 encode non-ASCII characters.");
72-
}
62+
}
63+
64+
var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
65+
i = 0,
66+
cur, prev, byteNum,
67+
result=[];
7368

74-
//create an array of binary digits representing the text
7569
while(i < text.length){
76-
part = text.charCodeAt(i).toString(2);
77-
bits = bits.concat(padLeft(part.split(""), 8));
78-
i++;
79-
}
80-
81-
//figure out how many 24-bit quanta are in the array
82-
quantaCount = Math.floor(bits.length / 24);
83-
84-
//encode all bits
85-
encodeBits: while(true){
86-
87-
//must encode one complete quanta at a time
88-
for(i=0; i < quantaCount; i++){
89-
for (j=0; j < 4 && bits.length; j++){
90-
part = bits.splice(0, 6).join("");
91-
index = parseInt(part,2);
92-
result.push(digits.charAt(index));
93-
}
94-
}
70+
71+
cur = text.charCodeAt(i);
72+
byteNum = i % 3;
73+
74+
switch(byteNum){
75+
case 0: //first byte
76+
result.push(digits.charAt(cur >> 2));
77+
break;
78+
79+
case 1: //second byte
80+
result.push(digits.charAt((prev & 3) << 4 | (cur >> 4)));
81+
break;
9582

96-
//take care of any extra bits
97-
switch(bits.length){
98-
case 8:
99-
padRight(bits, 12);
100-
padding = "==";
101-
quantaCount = 1;
102-
continue encodeBits;
103-
case 16:
104-
padRight(bits, 18);
105-
padding = "=";
106-
quantaCount = 1;
107-
continue encodeBits;
108-
default:
109-
break encodeBits;
83+
case 2: //third byte
84+
result.push(digits.charAt((prev & 0x0f) << 2 | (cur >> 6)));
85+
result.push(digits.charAt(cur & 0x3f));
86+
break;
11087
}
88+
89+
prev = cur;
90+
i++;
11191
}
11292

113-
//add any padding to the result
114-
result.push(padding);
115-
116-
//return a string
93+
if (byteNum == 0){
94+
result.push(digits.charAt((prev & 3) << 4));
95+
result.push("==");
96+
} else if (byteNum == 1){
97+
result.push(digits.charAt((prev & 0x0f) << 2));
98+
result.push("=");
99+
}
100+
117101
return result.join("");
118-
119102
}
120103

121104
/**

0 commit comments

Comments
 (0)