Skip to content

Commit cb03b4c

Browse files
author
Nicholas C. Zakas
committed
Updated base64Decode() with simpler implementation
1 parent 198229b commit cb03b4c

File tree

1 file changed

+33
-40
lines changed

1 file changed

+33
-40
lines changed

encodings/base64/base64.js

Lines changed: 33 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -107,53 +107,46 @@ function base64Encode(text){
107107
* @return {String} The base64-decoded string.
108108
*/
109109
function base64Decode(text){
110-
111-
//local variables
112-
var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
113-
part, code,
114-
i=0, j=0,
115-
padCount=0,
116-
bits = [],
117-
result = [];
118110

119111
//first check for any unexpected input
120112
if(!(/^[a-z0-9\+\/\s]+\={0,2}$/i.test(text))){
121113
throw new Error("Not a base64-encode string.");
122-
}
123-
124-
//remove any whitespace
125-
text = text.replace(/\s/g, "");
126-
127-
//determine if there's any padding
128-
while(text.charAt(text.length-1) == "="){
129-
130-
//increment pad count
131-
padCount += 2;
132-
133-
//remove last character and try again
134-
text = text.substr(0, text.length-1);
135114
}
136-
137-
//create an array of binary digits representing the text
138-
while (i < text.length){
139-
part = digits.indexOf(text.charAt(i)).toString(2);
140-
bits = bits.concat(padLeft(part.split(""), 6));
141-
i++;
142-
}
143115

144-
//remove padding
145-
bits = bits.slice(0, bits.length - padCount);
146-
147-
//if there's not enough bits, probably means an equals sign is missing
148-
//remove the extra bits
149-
if (bits.length % 8 != 0){
150-
bits = bits.slice(0, bits.length - bits.length % 8);
151-
}
116+
//local variables
117+
var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
118+
cur, prev, digitNum,
119+
i=0,
120+
result = [];
152121

153-
//transform what remains back into characters
154-
while(bits.length){
155-
part = bits.splice(0, 8).join("");
156-
result.push(String.fromCharCode(parseInt(part, 2)));
122+
//remove any whitespace and equals signs
123+
text = text.replace(/[\s=]/g, "");
124+
125+
//loop over each character
126+
while(i < text.length){
127+
128+
cur = digits.indexOf(text.charAt(i));
129+
digitNum = i % 4;
130+
131+
switch(digitNum){
132+
133+
//case 0: do nothing, not enough info to work with
134+
135+
case 1: //second digit
136+
result.push(String.fromCharCode(prev << 2 | cur >> 4));
137+
break;
138+
139+
case 2: //third digit
140+
result.push(String.fromCharCode((prev & 0x0f) << 4 | cur >> 2));
141+
break;
142+
143+
case 3: //fourth digit
144+
result.push(String.fromCharCode((prev & 3) << 6 | cur));
145+
break;
146+
}
147+
148+
prev = cur;
149+
i++;
157150
}
158151

159152
//return a string

0 commit comments

Comments
 (0)