Thursday, 15 September 2011

javascript - Why does this code have 3 octets over 4 characters? -



javascript - Why does this code have 3 octets over 4 characters? -

i'm trying understand this javascript base64 decoding code i'm puzzled loop @ lines 70-84:

for (i=0; i<bytes; i+=3) { //get 3 octects in 4 ascii chars enc1 = this._keystr.indexof(input.charat(j++)); enc2 = this._keystr.indexof(input.charat(j++)); enc3 = this._keystr.indexof(input.charat(j++)); enc4 = this._keystr.indexof(input.charat(j++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; uarray[i] = chr1; if (enc3 != 64) uarray[i+1] = chr2; if (enc4 != 64) uarray[i+2] = chr3; }

specifically, i'd know why there 3 octets in 4 ascii chars. shouldn't there 4 octets?

because 3 octets requires 24 bits of storage. in base of operations 64 have 6 bits per character (ascii character). 4 characters * 6 bits = 24 bit, 24-bits requires 4 base64 characters.

javascript base64

No comments:

Post a Comment