[whatwg] BinaryEncoding for Typed Arrays using window.btoa and window.atob

Chang Shu cshu01 at gmail.com
Mon Aug 5 07:12:32 PDT 2013

Hi, all,

Based on the discussion in Blink-dev mail group,
particularly from Adam Bath's suggestion, I drafted a proposal for
binary encoding on Typed Arrays by enhancing window.btoa and atob

The text of the proposal is pasted as below. I appreciate your kind review.



Proposed Binary Encoding Web API for Typed Arrays

Chang Shu (Samsung Electronics)


This specification enhances the existing window.btoa and window.atob
Web APIs to encode directly from Typed Arrays to Base64 strings and
vice versa.

Use Case Description

A webapp sends data from Typed Array to NPAPI plugin and also reads
data back. Since the only possible data type supported by NPAPI to
send data buffer is text string, an efficient way of converting Typed
Array to Base64 string is required.

Current Limitations

The only existing Web API involving binary data encoding are
window.btoa and window.atob. However, they require the raw data being
contained in a 'binary' string format while in many cases the raw data
is stored in Typed Array.

Current Usage and Workarounds

Currently, converting Typed Array to 'binary' string can be done in JS
functions. But performance is not acceptable for large data buffers.


The new enhancement of btoa and atob converts the raw data in Typed
Arrays to text string and from text string to Typed Arrays directly.
The performance is the best since all operations are done in native

Requests for this Feature

I would like this feature to be implemented and shipped.

Proposed Solutions

My Solution

The approach is to enhance existing btoa and atob to take Typed Array
parameters while keeping backward compatibility.



Creates a base-64 encoded ASCII string from either a "string" of
binary data or a Typed Array.


var encodedData = window.btoa(dataToEncode);

Note that there is no syntax change in window.btoa API.


var encodedData = window.btoa("hello"); //encode a string. Consider
the string as 'binary'

var arr = new Int32Array(3);
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
var encodedData = window.btoa(arr); //encode integer data into a base-64 string



Decodes a base-64 encoded ASCII string into a "string" of binary data
and a Typed Array if parameter provided.


var decodedArr = new Int32Array();
var decodedData = window.atob(encodedData, [Optinoal] decodedArr);

Note that the 2nd parameter is optional which keeps the backward compatibility.


var arr = new Int32Array(3);
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
var encodedData = window.btoa(arr); //encode integer data into a base-64 string

var newarr = new Int32Array();
window.atob(encodedData, newarr); //decode base-64 string back to integer array
//newarr[0] should be 1, newarr[1] should be 2 and newarr[2] should be 3.

More information about the whatwg mailing list