js中字串轉base64以及base64轉字串原理及實現

今天刷codewars的題目的時候碰到一個透過js來實現字串轉base64的題目,base64雖然在js或nodejs中經常用,但是我還真沒有仔細去看過原理以及如何實現,這回繞不過去了,趕緊找了找資料看了下。

先貼下參考資料

維基base64:

https://en。wikipedia。org/wiki/Base64

再貼下我個人粗淺的理解(不包括中文)

字串轉成base64 是對照碼錶來進行轉化的,比如字串

abc

,將每個字元轉成8位的二進位制資料,然後將三個8位二進位制組合起來,按照每6位一個字元重新轉化,然後對照碼錶獲得字元,當原資料不是3的整數倍時,如果最後剩下兩個輸入資料,在編碼結果後加1個“=;如果最後剩下一個輸入資料,編碼結果後加2個“=;如果沒有剩下任何資料,就什麼都不要加,這樣才可以保證資料還原的正確性。

js中字串轉base64以及base64轉字串原理及實現

base64 table index

以下以

abcd

進行舉例。 abc 對應的二進位制字串為:

1100001_1100010_1100011_1100100

,然後將每個字元換成8位的資料,沒有則前面補充0,變為

01100001_01100010_01100011_01100100

,然後將轉化後的字元按照每6位分割,變為

011000_010110_001001_100011_011001_00xxxx

,如果不足六位則後面補充0,變為

011000_010110_001001_100011_011001_000000

。按照我粗淺的理解就是最後補充了4個0,那就加兩個=,補充了兩個0那就加1個=。具體講解可以看維基。

js中字串轉base64以及base64轉字串原理及實現

維基講解

那麼,我們就可以按照上面的思路來進行一步一步的轉化,當然,從base64轉成字串就相當於逆向操作是一樣一樣滴。

程式碼實現

String。prototype。toBase64 = function(){ //字串轉base64,轉為二級制(補全8位),然後按照6位(最高64)分割,然後補充後導0,新增= let code = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/’, str = this, res = ‘’, binaryStr = ‘’; for(let i=0,max = str。length;i 0){ let index = parseInt(temp,2); let char = String。fromCodePoint(Math。abs(index)); res += char; } } return res;}var a = ‘abcd’。toBase64();console。log(a);console。log(a。fromBase64())//YWJjZA==//abcd

以上程式碼不支援中文,而且效能和效率上也很差,主要是為了方便理解base64的轉化,至於拿來用在生產的程式碼可以從網上找些,都是比較相似的。

/*** UTF16和UTF8轉換對照表* U+00000000 – U+0000007F 0xxxxxxx* U+00000080 – U+000007FF 110xxxxx 10xxxxxx* U+00000800 – U+0000FFFF 1110xxxx 10xxxxxx 10xxxxxx* U+00010000 – U+001FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx* U+00200000 – U+03FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx* U+04000000 – U+7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx*/var Base64 = { // 轉碼錶 table : [ ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’, ‘M’, ‘N’, ‘O’ ,‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’, ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘+’, ‘/’ ], UTF16ToUTF8 : function(str) { var res = [], len = str。length; for (var i = 0; i < len; i++) { var code = str。charCodeAt(i); if (code > 0x0000 && code <= 0x007F) { // 單位元組,這裡並不考慮0x0000,因為它是空位元組 // U+00000000 – U+0000007F 0xxxxxxx res。push(str。charAt(i)); } else if (code >= 0x0080 && code <= 0x07FF) { // 雙位元組 // U+00000080 – U+000007FF 110xxxxx 10xxxxxx // 110xxxxx var byte1 = 0xC0 | ((code >> 6) & 0x1F); // 10xxxxxx var byte2 = 0x80 | (code & 0x3F); res。push( String。fromCharCode(byte1), String。fromCharCode(byte2) ); } else if (code >= 0x0800 && code <= 0xFFFF) { // 三位元組 // U+00000800 – U+0000FFFF 1110xxxx 10xxxxxx 10xxxxxx // 1110xxxx var byte1 = 0xE0 | ((code >> 12) & 0x0F); // 10xxxxxx var byte2 = 0x80 | ((code >> 6) & 0x3F); // 10xxxxxx var byte3 = 0x80 | (code & 0x3F); res。push( String。fromCharCode(byte1), String。fromCharCode(byte2), String。fromCharCode(byte3) ); } else if (code >= 0x00010000 && code <= 0x001FFFFF) { // 四位元組 // U+00010000 – U+001FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx } else if (code >= 0x00200000 && code <= 0x03FFFFFF) { // 五位元組 // U+00200000 – U+03FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx } else /** if (code >= 0x04000000 && code <= 0x7FFFFFFF)*/ { // 六位元組 // U+04000000 – U+7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx } } return res。join(‘’); }, UTF8ToUTF16 : function(str) { var res = [], len = str。length; var i = 0; for (var i = 0; i < len; i++) { var code = str。charCodeAt(i); // 對第一個位元組進行判斷 if (((code >> 7) & 0xFF) == 0x0) { // 單位元組 // 0xxxxxxx res。push(str。charAt(i)); } else if (((code >> 5) & 0xFF) == 0x6) { // 雙位元組 // 110xxxxx 10xxxxxx var code2 = str。charCodeAt(++i); var byte1 = (code & 0x1F) << 6; var byte2 = code2 & 0x3F; var utf16 = byte1 | byte2; res。push(Sting。fromCharCode(utf16)); } else if (((code >> 4) & 0xFF) == 0xE) { // 三位元組 // 1110xxxx 10xxxxxx 10xxxxxx var code2 = str。charCodeAt(++i); var code3 = str。charCodeAt(++i); var byte1 = (code << 4) | ((code2 >> 2) & 0x0F); var byte2 = ((code2 & 0x03) << 6) | (code3 & 0x3F); var utf16 = ((byte1 & 0x00FF) << 8) | byte2 res。push(String。fromCharCode(utf16)); } else if (((code >> 3) & 0xFF) == 0x1E) { // 四位元組 // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx } else if (((code >> 2) & 0xFF) == 0x3E) { // 五位元組 // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx } else /** if (((code >> 1) & 0xFF) == 0x7E)*/ { // 六位元組 // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx } } return res。join(‘’); }, encode : function(str) { if (!str) { return ‘’; } var utf8 = this。UTF16ToUTF8(str); // 轉成UTF8 var i = 0; // 遍歷索引 var len = utf8。length; var res = []; while (i < len) { var c1 = utf8。charCodeAt(i++) & 0xFF; res。push(this。table[c1 >> 2]); // 需要補2個= if (i == len) { res。push(this。table[(c1 & 0x3) << 4]); res。push(‘==’); break; } var c2 = utf8。charCodeAt(i++); // 需要補1個= if (i == len) { res。push(this。table[((c1 & 0x3) << 4) | ((c2 >> 4) & 0x0F)]); res。push(this。table[(c2 & 0x0F) << 2]); res。push(‘=’); break; } var c3 = utf8。charCodeAt(i++); res。push(this。table[((c1 & 0x3) << 4) | ((c2 >> 4) & 0x0F)]); res。push(this。table[((c2 & 0x0F) << 2) | ((c3 & 0xC0) >> 6)]); res。push(this。table[c3 & 0x3F]); } return res。join(‘’); }, decode : function(str) { if (!str) { return ‘’; } var len = str。length; var i = 0; var res = []; while (i < len) { code1 = this。table。indexOf(str。charAt(i++)); code2 = this。table。indexOf(str。charAt(i++)); code3 = this。table。indexOf(str。charAt(i++)); code4 = this。table。indexOf(str。charAt(i++)); c1 = (code1 << 2) | (code2 >> 4); res。push(String。fromCharCode(c1)); if (code3 != -1) { c2 = ((code2 & 0xF) << 4) | (code3 >> 2); res。push(String。fromCharCode(c2)); } if (code4 != -1) { c3 = ((code3 & 0x3) << 6) | code4; res。push(String。fromCharCode(c3)); } } return this。UTF8ToUTF16(res。join(‘’)); }};var msg = ‘Hello, oschina!又是一年春來到~!’;console。group(‘Test Base64: ’);var b64 = Base64。encode(msg);console。log(b64);d64 = Base64。decode(b64);console。log(d64, d64 === msg);console。groupEnd();

以上為js中字串轉base64的個人理解,僅供參考!