@@ -107,53 +107,46 @@ function base64Encode(text){
107
107
* @return {String } The base64-decoded string.
108
108
*/
109
109
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 = [ ] ;
118
110
119
111
//first check for any unexpected input
120
112
if ( ! ( / ^ [ a - z 0 - 9 \+ \/ \s ] + \= { 0 , 2 } $ / i. test ( text ) ) ) {
121
113
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 ) ;
135
114
}
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
- }
143
115
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 = [ ] ;
152
121
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 ++ ;
157
150
}
158
151
159
152
//return a string
0 commit comments