@@ -56,66 +56,49 @@ function padRight(bits, length){
56
56
* @return {String } The base64-encoded string.
57
57
*/
58
58
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 = [ ] ;
68
59
69
- //verify that there are no characters out of range
70
60
if ( / ( [ ^ \u0000 - \u00ff ] ) / . test ( text ) ) {
71
61
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 = [ ] ;
73
68
74
- //create an array of binary digits representing the text
75
69
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 ;
95
82
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 ;
110
87
}
88
+
89
+ prev = cur ;
90
+ i ++ ;
111
91
}
112
92
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
+
117
101
return result . join ( "" ) ;
118
-
119
102
}
120
103
121
104
/**
0 commit comments