aboutsummaryrefslogtreecommitdiff
path: root/files/ja/glossary/base64/index.html
blob: 1091cf14aa344b617f6436ad979207097333c7d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
---
title: Base64 のエンコードとデコード
slug: Glossary/Base64
tags:
  - Advanced
  - Base64
  - JavaScript
  - Typed Arrays
  - URI
  - URL
  - Unicode Problem
  - atob()
  - btoa()
translation_of: Glossary/Base64
original_slug: Web/API/WindowBase64/Base64_encoding_and_decoding
---
<p><strong>Base64</strong> とは、<a href="https://en.wikipedia.org/wiki/Binary-to-text_encoding">バイナリーからテキストへの符号化</a>を行う手法のグループであり、64 を基数とする表現に変換することで、バイナリーデータを ASCII 文字列で表すことができます。<em>Base64</em> という呼び方は、<a href="https://ja.wikipedia.org/wiki/MIME#Content-Transfer-Encoding">MIME の Content-Transfer-Encoding</a> における特定の符号化方式の名前に由来します。</p>

<p>Base64 符号化方式がよく使われるのは、テキストデータを扱うよう設計されたメディア上で、バイナリーデータを格納または転送する必要がある場合です。Base64 符号化により、転送中に変換されることなく、バイナリーデータがそのままであることを保証できます。Base64 は、<a href="https://ja.wikipedia.org/wiki/MIME">MIME</a> による電子メールや <a href="/ja/docs/XML">XML</a> における複合型データの格納など、多くのアプリケーションで幅広く使われています。</p>

<p>JavaScript には、Base64 文字列のエンコードとデコードのそれぞれに対応した、次の 2 つの関数があります。</p>

<ul>
 <li>{{domxref("WindowBase64.atob","atob()")}}</li>
 <li>{{domxref("WindowBase64.btoa","btoa()")}}</li>
</ul>

<p><code>atob()</code> 関数は、Base64 符号化方式によりエンコードされている文字列をデコードしてバイナリー文字列を作ります。逆に <code>btoa()</code> 関数は、バイナリー文字列から Base64 でエンコードされた ASCII 文字列を作ります。</p>

<p><code>atob()</code><code>btoa()</code> のどちらも、文字列に対して動作します。もし <a href="/ja/docs/Web/API/ArrayBuffer"><code>ArrayBuffer</code></a> に対して動作させたい場合は、<a href="/ja/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_5">この段落</a> を読んでください。</p>

<h4 id="Encoded_size_increase" name="Encoded_size_increase">符号化によるサイズ増加</h4>

<p>Base64 の 1 文字はデータのちょうど 6 ビット分を表します。そのため、入力される文字列やバイナリーファイルに含まれる 3 バイト (3×8 ビット = 24 ビット) は、4 桁の Base64 で表されます (4×6 = 24 ビット)。</p>

<p>このことにより、Base64 で表された文字列またはファイルは、元のサイズの 133% の大きさになると言えます (33% の増加)。エンコードされるデータが小さい場合は、さらに増加幅が大きくなります。例えば、<code>length === 1</code> である文字列 <code>"a"</code> は、エンコードされて <code>length === 4</code> の文字列 <code>"YQ=="</code> になり、これは 300% の増加です。</p>

<table class="topicpage-table">
 <tbody>
  <tr>
   <td>
    <h2 class="Documentation" id="Documentation" name="Documentation">参考文書</h2>

    <dl>
     <dt><a href="https://developer.mozilla.org/ja/docs/data_URIs">データ URL</a></dt>
     <dd><small>データ URL は、<a class="external" href="http://tools.ietf.org/html/rfc2397">RFC 2397</a> により定義されており、 これにより文書中に小さなファイルを埋め込むことができます。</small></dd>
     <dt><a href="https://ja.wikipedia.org/wiki/Base64">Base64</a></dt>
     <dd><small>ウィキペディアの Base64 符号化方式に関する記事です。</small></dd>
     <dt><a href="https://html.spec.whatwg.org/multipage/webappapis.html#windoworworkerglobalscope-mixin">WindowOrWorkerGlobalScope ミックスイン</a></dt>
     <dd><code>atob</code><code>btoa</code> を規定し、これらは <a href="https://tools.ietf.org/html/rfc4648">RFC 4648</a> により規定された Base64 にエンコードすると定めています。</dd>
     <dt><a href="https://tools.ietf.org/html/rfc4648">RFC 4648</a></dt>
     <dd>セクション 4 で Base64 のアルゴリズムを規定し、またセクション 5 で URL 向けの "base64url" アルゴリズム (こちらは <code>atob</code><code>btoa</code> では使われない) も定義しています。</dd>
     <dt>{{domxref("WindowBase64.atob","atob()")}}</dt>
     <dd><small>Base64 によりエンコードされている ASCII 文字列をデコードして、バイナリー文字列を作ります。</small></dd>
     <dt>{{domxref("WindowBase64.btoa","btoa()")}}</dt>
     <dd><small>バイナリー文字列から、Base64 によりエンコードされた ASCII 文字列を作ります。</small></dd>
     <dt><a href="#The_Unicode_Problem">あの「Unicode の問題」</a></dt>
     <dd><small>ほとんどのブラウザーでは、Unicode 文字列を使って <code>btoa()</code> を実行すると、<code>Character Out Of Range</code> 例外が発生します。この段落では、これに対するいくつかの対策を説明しています。</small></dd>
     <dt><a href="/ja/docs/URIScheme">URIScheme</a></dt>
     <dd><small>Mozilla のサポートした URI スキームのリスト</small></dd>
     <dt><a href="/ja/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code></a></dt>
     <dd>この記事では、次を狙いとしたライブラリーを公開しています
     <ul>
      <li>文字列に対する <a href="https://ja.wikipedia.org/wiki/C%E8%A8%80%E8%AA%9E">C 言語</a>に似たインターフェイス (すなわち文字のコードの配列であり、JavaScript では <a href="/ja/docs/Web/JavaScript/Typed_arrays/ArrayBufferView"><code>ArrayBufferView</code></a>) を JavaScript の <a href="/ja/docs/Web/JavaScript/Typed_arrays/ArrayBuffer"><code>ArrayBuffer</code></a> インターフェイスを使って作ること</li>
      <li>文字列に似たオブジェクト (これからは <code>stringView</code>) 向けの、不変である JavaScript 文字列に対してではなく<strong>必ず数値の配列に対して</strong>働く、メソッドのコレクションを作ること</li>
      <li>JavaScript デフォルトである UTF-16 の <a href="/ja/docs/Web/API/DOMString"><code>DOMString</code></a> 以外の Unicode でも動作すること</li>
     </ul>
     </dd>
    </dl>

    <p><span class="alllinks"><a href="/ja/docs/tag/Base64">全て表示...</a></span></p>
   </td>
   <td>
    <h2 class="Tools" id="Tools" name="Tools">ツール</h2>

    <ul>
     <li><a href="#Solution_5_–_rewrite_the_DOMs_atob_and_btoa_using_JavaScripts_TypedArrays_and_UTF-8">atob() and btoa() を TypedArrays および UTF-8 で書き直す</a></li>
     <li><a href="/ja/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – 型付き配列に基づく C 言語に似た文字列表現</a></li>
    </ul>

    <p><span class="alllinks"><a href="/ja/docs/tag/Base64">全て表示...</a></span></p>

    <h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">関連するトピックス</h2>

    <ul>
     <li><a href="/ja/docs/Web/JavaScript/Typed_arrays/ArrayBuffer"><code>ArrayBuffer</code></a></li>
     <li><a href="/ja/docs/Web/JavaScript/Typed_arrays">JavaScript 型付き配列</a></li>
     <li><code><a href="/ja/docs/Web/JavaScript/Typed_arrays/ArrayBufferView">ArrayBufferView</a></code></li>
     <li><a href="/ja/docs/Web/JavaScript/Typed_arrays/Uint8Array"><code>Uint8Array</code></a></li>
     <li><a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – 型付き配列に基づく C 言語に似た文字列表現</a></li>
     <li><a href="/ja/docs/Web/API/DOMString"><code>DOMString</code></a></li>
     <li><a href="/ja/docs/Glossary/URI"><code>URI</code></a></li>
     <li><a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/encodeURI"><code>encodeURI()</code></a></li>
    </ul>
   </td>
  </tr>
 </tbody>
</table>

<h2 id="The_Unicode_Problem" name="The_Unicode_Problem">あの「Unicode の問題」</h2>

<p><a href="/ja/docs/Web/API/DOMString"><code>DOMString</code></a> は 16 ビットで符号化された文字列であるので、Unicode 文字列を使って <code>window.btoa</code> を実行すると、8 ビットの範囲 (0x00~0xFF) を超えた文字がある場合に、ほとんどのブラウザーで <code>Character Out Of Range</code> 例外が発生します。以下は、この問題を解決するための 5 つの方法です。</p>

<ul>
 <li><a href="#Solution_1_–_JavaScript's_UTF-16_>_base64">最初の方法</a>は、JavaScript のネイティブ UTF-16 文字列を直接 Base64 にエンコードします (高速で、移植性があり、クリーン)</li>
 <li><a href="#Solution_2_–_JavaScript's_UTF-16_>_UTF-8_>_base64">2 番目の方法</a>は、JavaScript のネイティブ UTF-16 文字列を UTF-8 に変換し、その後 Base64 にエンコードします (比較的高速で、移植性があり、クリーン)</li>
 <li><a href="#Solution_3_–_JavaScript's_UTF-16_>_binary_string_>_base64">3 番目の方法</a>は、JavaScript のネイティブ UTF-16 文字列を、バイナリー文字列経由で、Base64 にエンコードします (非常に高速で、比較的移植性があり、非常にコンパクト)</li>
 <li><a href="#Solution_4_–_escaping_the_string_before_encoding_it">4 番目の方法</a>は、文字列全体をエスケープし (UTF-8 を使う。{{jsxref("encodeURIComponent")}} を参照)、そしてエンコードします (移植性はあるが、非標準的)</li>
 <li><a href="#Solution_5_–_rewrite_the_DOMs_atob()_and_btoa()_using_JavaScript's_TypedArrays_and_UTF-8">5 番目の方法</a>は、2 番目の方法と似ていますが、サードパーティのライブラリを使います</li>
</ul>

<h3 id="Solution_1_–_JavaScripts_UTF-16_>_base64" name="Solution_1_–_JavaScripts_UTF-16_>_base64">方法 1 – JavaScript の UTF-16 =&gt; Base64</h3>

<p>Unicode 問題を解決する、非常に高速で幅広く使われている方法は、JavaScript のネイティブ UTF-16 文字列を直接 Base64 にエンコードすることです。デモのために URL <code>data:text/plain;charset=utf-16;base64,OCY5JjomOyY8Jj4mPyY=</code> を開いてください (このデータ URL をコピーし、新しいタブを開き、データ URL をアドレスバーに貼り付け、エンターをを押す)。この方法は、文字列を配列に割り当てるところを除き、どのような種類の変換も必要としないため、特に効率的です。次のコードは、Base64 文字列から <a href="/ja/docs/Web/JavaScript/Typed_arrays/ArrayBuffer">ArrayBuffer</a> に変換したり、その逆変換をするのにも便利です (<a href="#Appendix_to_Solution_1">下記参照</a>)。</p>

<pre class="brush: js">"use strict";

/*\
|*|
|*|  Base64 / binary data / UTF-8 strings utilities (#1)
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
|*|
|*|  Author: madmurphy
|*|
\*/

/* Array of bytes to base64 string decoding */

function b64ToUint6 (nChr) {

  return nChr &gt; 64 &amp;&amp; nChr &lt; 91 ?
      nChr - 65
    : nChr &gt; 96 &amp;&amp; nChr &lt; 123 ?
      nChr - 71
    : nChr &gt; 47 &amp;&amp; nChr &lt; 58 ?
      nChr + 4
    : nChr === 43 ?
      62
    : nChr === 47 ?
      63
    :
      0;

}

function base64DecToArr (sBase64, nBlockSize) {

  var
    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
    nOutLen = nBlockSize ? Math.ceil((nInLen * 3 + 1 &gt;&gt;&gt; 2) / nBlockSize) * nBlockSize : nInLen * 3 + 1 &gt;&gt;&gt; 2, aBytes = new Uint8Array(nOutLen);

  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx &lt; nInLen; nInIdx++) {
    nMod4 = nInIdx &amp; 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) &lt;&lt; 18 - 6 * nMod4;
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 &lt; 3 &amp;&amp; nOutIdx &lt; nOutLen; nMod3++, nOutIdx++) {
        aBytes[nOutIdx] = nUint24 &gt;&gt;&gt; (16 &gt;&gt;&gt; nMod3 &amp; 24) &amp; 255;
      }
      nUint24 = 0;
    }
  }

  return aBytes;
}

/* Base64 string to array encoding */

function uint6ToB64 (nUint6) {

  return nUint6 &lt; 26 ?
      nUint6 + 65
    : nUint6 &lt; 52 ?
      nUint6 + 71
    : nUint6 &lt; 62 ?
      nUint6 - 4
    : nUint6 === 62 ?
      43
    : nUint6 === 63 ?
      47
    :
      65;

}

function base64EncArr (aBytes) {

  var eqLen = (3 - (aBytes.length % 3)) % 3, sB64Enc = "";

  for (var nMod3, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx &lt; nLen; nIdx++) {
    nMod3 = nIdx % 3;
    /* Uncomment the following line in order to split the output in lines 76-character long: */
    /*
    if (nIdx &gt; 0 &amp;&amp; (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
    */
    nUint24 |= aBytes[nIdx] &lt;&lt; (16 &gt;&gt;&gt; nMod3 &amp; 24);
    if (nMod3 === 2 || aBytes.length - nIdx === 1) {
      sB64Enc += String.fromCharCode(uint6ToB64(nUint24 &gt;&gt;&gt; 18 &amp; 63), uint6ToB64(nUint24 &gt;&gt;&gt; 12 &amp; 63), uint6ToB64(nUint24 &gt;&gt;&gt; 6 &amp; 63), uint6ToB64(nUint24 &amp; 63));
      nUint24 = 0;
    }
  }

  return  eqLen === 0 ?
      sB64Enc
    :
      sB64Enc.substring(0, sB64Enc.length - eqLen) + (eqLen === 1 ? "=" : "==");

}
</pre>

<h4 id="Tests" name="Tests">テスト</h4>

<pre class="brush: js">var myString = "☸☹☺☻☼☾☿";

/* Part 1: `myString` をネイティブの UTF-16 を使って Base64 にエンコードする */

var aUTF16CodeUnits = new Uint16Array(myString.length);
Array.prototype.forEach.call(aUTF16CodeUnits, function (el, idx, arr) { arr[idx] = myString.charCodeAt(idx); });
var sUTF16Base64 = base64EncArr(new Uint8Array(aUTF16CodeUnits.buffer));

/* 出力を表示する */

alert(sUTF16Base64); // "OCY5JjomOyY8Jj4mPyY="

/* Part 2: `sUTF16Base64` を UTF-16 にデコードする */

var sDecodedString = String.fromCharCode.apply(null, new Uint16Array(base64DecToArr(sUTF16Base64, 2).buffer));

/* 出力を表示する */

alert(sDecodedString); // "☸☹☺☻☼☾☿"</pre>

<p>生成された Base64 文字列はどこでも使えますが、UTF-16 で表現されています。もし UTF-8 を望む場合は<a href="#Solution_2_–_JavaScript's_UTF-16_>_UTF-8_>_base64">次の方法</a>を参照してください。</p>

<h4 id="Appendix_to_Solution_1_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer" name="Appendix_to_Solution_1_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer"><a href="#Solution_1_–_JavaScript's_UTF-16_>_base64">方法 1</a> に対する補足: <em>Base64</em> 文字列を <a href="/ja/docs/Web/JavaScript/Typed_arrays/Uint8Array">Uint8Array</a><a href="/ja/docs/Web/JavaScript/Typed_arrays/ArrayBuffer">ArrayBuffer</a> にデコードする</h4>

<p>上記の関数を使って、<em>Base64</em> でエンコードされた文字列から <a href="/ja/docs/Web/JavaScript/Typed_arrays/Uint8Array">Uint8Array</a><a href="/ja/docs/Web/JavaScript/Typed_arrays/ArrayBuffer">ArrayBuffer</a> を作ることもできます。</p>

<pre class="brush: js">var myArray = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw=="); // "Base 64 \u2014 Mozilla Developer Network" (as UTF-8)

var myBuffer = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw==").buffer; // "Base 64 \u2014 Mozilla Developer Network" (as UTF-8)

alert(myBuffer.byteLength);</pre>

<div class="note"><strong>注意:</strong> 関数 <code>base64DecToArr(sBase64[, <em>nBlockSize</em>])</code> は、8 ビットの <a href="/ja/docs/Web/JavaScript/Typed_arrays/Uint8Array"><code>Uint8Array</code></a> を返します。もし 16 ビット / 32 ビット / 64 ビットの生データのバッファを作ることが目的であれば、引数 <code>nBlockSize</code> を使ってください。これはバイト数であり、<code>Uint8Array.buffer.bytesLength</code> プロパティはその倍数になります (<code>1</code> や省略された場合は ASCII、バイナリーデータ、<a href="https://developer.mozilla.org/ja/docs/Web/API/DOMString/Binary">バイナリー文字列</a>、UTF-8 文字列向けです。<code>2</code> は UTF-16 文字列向け、<code>4</code> は UTF-32 文字列向けです)。</div>

<p>完全なライブラリーは <a href="https://developer.mozilla.org/ja/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – 型付き配列に基づく C 言語に似た文字列表現</a> を参照してください (ソースコードは <a href="https://github.com/madmurphy/stringview.js">GitHub で利用できます</a>)。</p>

<h3 id="Solution_2_–_JavaScripts_UTF-16_>_UTF-8_>_base64" name="Solution_2_–_JavaScripts_UTF-16_>_UTF-8_>_base64">方法 2 – JavaScript の UTF-16 =&gt; UTF-8 =&gt; Base64</h3>

<p>この方法は、JavaScript ネイティブの UTF-16 文字列を UTF-8 文字列に変換し、それを Base64 でエンコードします。これにより、純粋な ASCII 文字列から Base64 への変換は、ネイティブの <code><a href="https://developer.mozilla.org/ja/docs/Web/API/WindowBase64/btoa">btoa()</a></code> のように、常に同じ結果を出力します。</p>

<pre class="brush: js">"use strict";

/*\
|*|
|*|  Base64 / binary data / UTF-8 strings utilities (#2)
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
|*|
|*|  Author: madmurphy
|*|
\*/

/* Array of bytes to base64 string decoding */

function b64ToUint6 (nChr) {

  return nChr &gt; 64 &amp;&amp; nChr &lt; 91 ?
      nChr - 65
    : nChr &gt; 96 &amp;&amp; nChr &lt; 123 ?
      nChr - 71
    : nChr &gt; 47 &amp;&amp; nChr &lt; 58 ?
      nChr + 4
    : nChr === 43 ?
      62
    : nChr === 47 ?
      63
    :
      0;

}

function base64DecToArr (sBase64, nBlockSize) {

  var
    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
    nOutLen = nBlockSize ? Math.ceil((nInLen * 3 + 1 &gt;&gt;&gt; 2) / nBlockSize) * nBlockSize : nInLen * 3 + 1 &gt;&gt;&gt; 2, aBytes = new Uint8Array(nOutLen);

  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx &lt; nInLen; nInIdx++) {
    nMod4 = nInIdx &amp; 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) &lt;&lt; 18 - 6 * nMod4;
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 &lt; 3 &amp;&amp; nOutIdx &lt; nOutLen; nMod3++, nOutIdx++) {
        aBytes[nOutIdx] = nUint24 &gt;&gt;&gt; (16 &gt;&gt;&gt; nMod3 &amp; 24) &amp; 255;
      }
      nUint24 = 0;
    }
  }

  return aBytes;
}

/* Base64 string to array encoding */

function uint6ToB64 (nUint6) {

  return nUint6 &lt; 26 ?
      nUint6 + 65
    : nUint6 &lt; 52 ?
      nUint6 + 71
    : nUint6 &lt; 62 ?
      nUint6 - 4
    : nUint6 === 62 ?
      43
    : nUint6 === 63 ?
      47
    :
      65;

}

function base64EncArr (aBytes) {

  var eqLen = (3 - (aBytes.length % 3)) % 3, sB64Enc = "";

  for (var nMod3, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx &lt; nLen; nIdx++) {
    nMod3 = nIdx % 3;
    /* Uncomment the following line in order to split the output in lines 76-character long: */
    /*
    if (nIdx &gt; 0 &amp;&amp; (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
    */
    nUint24 |= aBytes[nIdx] &lt;&lt; (16 &gt;&gt;&gt; nMod3 &amp; 24);
    if (nMod3 === 2 || aBytes.length - nIdx === 1) {
      sB64Enc += String.fromCharCode(uint6ToB64(nUint24 &gt;&gt;&gt; 18 &amp; 63), uint6ToB64(nUint24 &gt;&gt;&gt; 12 &amp; 63), uint6ToB64(nUint24 &gt;&gt;&gt; 6 &amp; 63), uint6ToB64(nUint24 &amp; 63));
      nUint24 = 0;
    }
  }

  return  eqLen === 0 ?
      sB64Enc
    :
      sB64Enc.substring(0, sB64Enc.length - eqLen) + (eqLen === 1 ? "=" : "==");

}

/* UTF-8 array to DOMString and vice versa */

function UTF8ArrToStr (aBytes) {

  var sView = "";

  for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx &lt; nLen; nIdx++) {
    nPart = aBytes[nIdx];
    sView += String.fromCharCode(
      nPart &gt; 251 &amp;&amp; nPart &lt; 254 &amp;&amp; nIdx + 5 &lt; nLen ? /* six bytes */
        /* (nPart - 252 &lt;&lt; 30) may be not so safe in ECMAScript! So...: */
        (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 &lt;&lt; 24) + (aBytes[++nIdx] - 128 &lt;&lt; 18) + (aBytes[++nIdx] - 128 &lt;&lt; 12) + (aBytes[++nIdx] - 128 &lt;&lt; 6) + aBytes[++nIdx] - 128
      : nPart &gt; 247 &amp;&amp; nPart &lt; 252 &amp;&amp; nIdx + 4 &lt; nLen ? /* five bytes */
        (nPart - 248 &lt;&lt; 24) + (aBytes[++nIdx] - 128 &lt;&lt; 18) + (aBytes[++nIdx] - 128 &lt;&lt; 12) + (aBytes[++nIdx] - 128 &lt;&lt; 6) + aBytes[++nIdx] - 128
      : nPart &gt; 239 &amp;&amp; nPart &lt; 248 &amp;&amp; nIdx + 3 &lt; nLen ? /* four bytes */
        (nPart - 240 &lt;&lt; 18) + (aBytes[++nIdx] - 128 &lt;&lt; 12) + (aBytes[++nIdx] - 128 &lt;&lt; 6) + aBytes[++nIdx] - 128
      : nPart &gt; 223 &amp;&amp; nPart &lt; 240 &amp;&amp; nIdx + 2 &lt; nLen ? /* three bytes */
        (nPart - 224 &lt;&lt; 12) + (aBytes[++nIdx] - 128 &lt;&lt; 6) + aBytes[++nIdx] - 128
      : nPart &gt; 191 &amp;&amp; nPart &lt; 224 &amp;&amp; nIdx + 1 &lt; nLen ? /* two bytes */
        (nPart - 192 &lt;&lt; 6) + aBytes[++nIdx] - 128
      : /* nPart &lt; 127 ? */ /* one byte */
        nPart
    );
  }

  return sView;

}

function strToUTF8Arr (sDOMStr) {

  var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0;

  /* mapping... */

  for (var nMapIdx = 0; nMapIdx &lt; nStrLen; nMapIdx++) {
    nChr = sDOMStr.charCodeAt(nMapIdx);
    nArrLen += nChr &lt; 0x80 ? 1 : nChr &lt; 0x800 ? 2 : nChr &lt; 0x10000 ? 3 : nChr &lt; 0x200000 ? 4 : nChr &lt; 0x4000000 ? 5 : 6;
  }

  aBytes = new Uint8Array(nArrLen);

  /* transcription... */

  for (var nIdx = 0, nChrIdx = 0; nIdx &lt; nArrLen; nChrIdx++) {
    nChr = sDOMStr.charCodeAt(nChrIdx);
    if (nChr &lt; 128) {
      /* one byte */
      aBytes[nIdx++] = nChr;
    } else if (nChr &lt; 0x800) {
      /* two bytes */
      aBytes[nIdx++] = 192 + (nChr &gt;&gt;&gt; 6);
      aBytes[nIdx++] = 128 + (nChr &amp; 63);
    } else if (nChr &lt; 0x10000) {
      /* three bytes */
      aBytes[nIdx++] = 224 + (nChr &gt;&gt;&gt; 12);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 6 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &amp; 63);
    } else if (nChr &lt; 0x200000) {
      /* four bytes */
      aBytes[nIdx++] = 240 + (nChr &gt;&gt;&gt; 18);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 12 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 6 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &amp; 63);
    } else if (nChr &lt; 0x4000000) {
      /* five bytes */
      aBytes[nIdx++] = 248 + (nChr &gt;&gt;&gt; 24);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 18 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 12 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 6 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &amp; 63);
    } else /* if (nChr &lt;= 0x7fffffff) */ {
      /* six bytes */
      aBytes[nIdx++] = 252 + (nChr &gt;&gt;&gt; 30);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 24 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 18 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 12 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &gt;&gt;&gt; 6 &amp; 63);
      aBytes[nIdx++] = 128 + (nChr &amp; 63);
    }
  }

  return aBytes;

}</pre>

<h4 id="Tests_2" name="Tests_2">テスト</h4>

<pre class="brush: js">/* テスト */

var sMyInput = "Base 64 \u2014 Mozilla Developer Network";

var aMyUTF8Input = strToUTF8Arr(sMyInput);

var sMyBase64 = base64EncArr(aMyUTF8Input);

alert(sMyBase64); // "QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw=="

var aMyUTF8Output = base64DecToArr(sMyBase64);

var sMyOutput = UTF8ArrToStr(aMyUTF8Output);

alert(sMyOutput); // "Base 64 — Mozilla Developer Network"</pre>

<h3 id="Solution_3_–_JavaScripts_UTF-16_>_binary_string_>_base64" name="Solution_3_–_JavaScripts_UTF-16_>_binary_string_>_base64">方法 3 – JavaScript の UTF-16 =&gt; バイナリー文字列 =&gt; Base64</h3>

<p>これは、最も速く最もコンパクトな方法です。出力は<a href="#Solution_1_–_JavaScript's_UTF-16_>_base64">方法 1</a> (UTF-16 ででエンコードされた文字列) のものと全く同じですが、{{domxref("WindowBase64.atob","atob()")}}{{domxref("WindowBase64.btoa","btoa()")}} を書き直すのではなく、ネイティブのものを使います。この方法はエンコードまたはデコードの入力として、型付き配列の代わりに、中間フォーマットである<a href="/ja/docs/Web/API/DOMString/Binary">バイナリー文字列</a>を使います。<a href="#Solution_1_–_JavaScript's_UTF-16_>_base64">方法 1</a> (<a href="/ja/docs/Web/API/DOMString/Binary">バイナリー文字列</a> は灰色の領域です) に比べると、これは「汚い」回避策ではありますが、問題なく動作し、必要なコードはわずか数行です。</p>

<pre class="brush: js">"use strict";

/*\
|*|
|*|  Base64 / binary data / UTF-8 strings utilities (#3)
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
|*|
|*|  Author: madmurphy
|*|
\*/

function btoaUTF16 (sString) {

	var aUTF16CodeUnits = new Uint16Array(sString.length);
	Array.prototype.forEach.call(aUTF16CodeUnits, function (el, idx, arr) { arr[idx] = sString.charCodeAt(idx); });
	return btoa(String.fromCharCode.apply(null, new Uint8Array(aUTF16CodeUnits.buffer)));

}

function atobUTF16 (sBase64) {

	var sBinaryString = atob(sBase64), aBinaryView = new Uint8Array(sBinaryString.length);
	Array.prototype.forEach.call(aBinaryView, function (el, idx, arr) { arr[idx] = sBinaryString.charCodeAt(idx); });
	return String.fromCharCode.apply(null, new Uint16Array(aBinaryView.buffer));

}</pre>

<h4 id="Tests_3" name="Tests_3">テスト</h4>

<pre class="brush: js">var myString = "☸☹☺☻☼☾☿";

/* Part 1: `myString` をネイティブの UTF-16 を使って Base64 にエンコードする */

var sUTF16Base64 = btoaUTF16(myString);

/* 出力を表示する */

alert(sUTF16Base64); // "OCY5JjomOyY8Jj4mPyY="

/* Part 2: `sUTF16Base64` を UTF-16 にデコードする */

var sDecodedString = atobUTF16(sUTF16Base64);

/* 出力を表示する */

alert(sDecodedString); // "☸☹☺☻☼☾☿"
</pre>

<p>バイナリー文字列の代わりに型付き配列を使う、よりクリーンな方法については、<a href="#Solution_1_–_JavaScript's_UTF-16_>_base64">方法 1</a><a href="#Solution_2_–_JavaScript's_UTF-16_>_UTF-8_>_base64">方法 2</a> を参照してください。</p>

<h3 id="Solution_4_–_escaping_the_string_before_encoding_it" name="Solution_4_–_escaping_the_string_before_encoding_it">方法 4 – エンコード前に文字列をエスケープ処理する</h3>

<pre class="brush:js">function b64EncodeUnicode(str) {
    // 最初に encodeURIComponent を使って "%" でエンコードされた UTF-8 文字列を取得し、
    // 次に "%" でエンコードされた文字列をバイナリー文字列に変換し、
    // それを btoa に与えます。
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
        function toSolidBytes(match, p1) {
            return String.fromCharCode('0x' + p1);
    }));
}

b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n'); // "Cg=="
</pre>

<p>Base64 でエンコードされた値を元の文字列に戻すには、次のようにします。</p>

<pre class="brush: js">function b64DecodeUnicode(str) {
    // 逆変換: バイナリー文字列から "%" エンコードへ、そしてオリジナルの文字列へ。
    return decodeURIComponent(atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
b64DecodeUnicode('Cg=='); // "\n"
</pre>

<p><a href="https://git.daplie.com/Daplie/unibabel-js">Unibabel</a> は、この方法を使った共通の変換を実装しています。</p>

<h3 id="Solution_5_–_rewrite_the_DOMs_atob_and_btoa_using_JavaScripts_TypedArrays_and_UTF-8" name="Solution_5_–_rewrite_the_DOMs_atob_and_btoa_using_JavaScripts_TypedArrays_and_UTF-8">方法 5 – DOM の <code>atob()</code><code>btoa()</code> を JavaScript の <code>TypedArray</code> と UTF-8 を使って書き換える</h3>

<p><a href="/ja/docs/Web/API/TextEncoder">TextEncoder</a> のポリフィル、例えば <a href="https://github.com/inexorabletash/text-encoding">TextEncoding</a> (レガシーの Windows、Mac、ISO のエンコーディングも含む) や <a href="https://github.com/coolaj86/TextEncoderLite">TextEncoderLite</a> を、モダンブラウザーと Node.js の両方で使える <a href="https://github.com/feross/buffer">Buffer</a> または <a href="https://github.com/beatgammit/base64-js">base64-js</a><a href="https://github.com/waitingsong/base64">TypeScript 版の </a>base64-js のような Base64 実装とを、組み合わせて使います。</p>

<p>ネイティブの TextEncoder 実装がない場合、最も軽量な方法は <a href="#Solution_3_–_JavaScript's_UTF-16_>_binary_string_>_base64">方法 3</a> でしょう。なぜなら、とても高速であることに加え、<a href="#Solution_3_–_JavaScript's_UTF-16_>_binary_string_>_base64">方法 3</a> は標準状態の IE9 でも動作するからです。 もう一つの方法は、<a href="https://github.com/coolaj86/TextEncoderLite">TextEncoderLite</a><a href="https://github.com/beatgammit/base64-js">base64-js</a> を使うことです。可能な場合はブラウザーの実装を使ってください。</p>

<p>次の関数は、この考えを実装したものです。これは、base64-js が <code>&lt;script type="text/javascript" src="base64js.min.js"/&gt;</code> のようにインポートされていることを前提にしています。TextEncoderLite は UTF-8 でのみ機能することに注意してください。</p>

<pre class="brush: js">function Base64Encode(str, encoding = 'utf-8') {
    var bytes = new (typeof TextEncoder === "undefined" ? TextEncoderLite : TextEncoder)(encoding).encode(str);
    return base64js.fromByteArray(bytes);
}

function Base64Decode(str, encoding = 'utf-8') {
    var bytes = base64js.toByteArray(str);
    return new (typeof TextDecoder === "undefined" ? TextDecoderLite : TextDecoder)(encoding).decode(bytes);
}
</pre>

<p><strong>Note</strong>: <a href="https://github.com/coolaj86/TextEncoderLite">TextEncoderLite</a> は、4 バイトの UTF-8 文字、つまり '\uD842\uDFB7' や '\u{20BB7}' のような文字を誤って解釈します。この <a href="https://github.com/solderjs/TextEncoderLite/issues/16">Issue</a> を参照してください。<br>
 あるいは、代わりに <a href="https://github.com/inexorabletash/text-encoding">text-encoding</a> を使ってください。</p>

<p>いくつかの場合には、UTF-8 に変換した後 Base64 にする上記の方法は、記憶領域に対してとても非効率的です。U+0800 から U+FFFF の範囲にある文字は、UTF-8 では 3 バイトにエンコードされますが UTF-16 では 2 バイトであり、これらがテキストの大部分を占める場合、UTF-8 の出力長は UTF-16 よりも長くなります。均等に分散した UTF-16 コードポイントを含む JavaScript 文字列の場合、Base64 の変換の前のエンコードを UTF-8 ではなく UTF-16 にすることで、サイズを 40% 減少できます。</p>