Use a DataView
:
function ArrayBufferToBit(buffer) {
var dataView = new DataView(buffer);
var response = "", offset = (8/8);
// I assume we will read the entire file as a series of 8-bit integers,
// i.e. as a byte, hence my choice of offset.
for(var i = 0; i < dataView.byteLength; i += offset) {
response += dataView.getInt8(i).toString(2);
// toString is the secret sauce here.
}
return response;
}
Dataview
s let you read/write numeric data; getInt8
converts the data from the byte position - here 0, the value passed in - in the ArrayBuffer
to signed 8-bit integer representation, and toString(2)
converts the 8-bit integer to binary representation format (i.e. a string of 1's and 0's).
The 'magic' offset value is obtained by noting we are taking files stored as bytes i.e. as 8-bit integers and reading it in 8-bit integer representation. If we were trying to read our byte-saved (i.e. 8 bits) files to 32-bit integers, we would note that 32/8 = 4 is the number of byte spaces, which is our byte offset value.
This, in addition to typed arrays, is the recommended way to read/write from an ArrayBuffer
:
The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
In addition to signed 8-bit representation, you can also get a variety of representations (like float64
or even int32
). The choice of representation should not matter, as toString(2)
will show it in binary anyway (though the length of your binary string certainly will change for obvious reasons!).
Note that in this example I have chosen to represent the entire file as a series of 8-bit integers i.e. reading byte by byte. In general, however, DataView
s facilitate the mixing of homogeneous types - you can read the first 12 bytes as 32-bit integers, and the remaining as 64-bit, for instance. DataView
s are usually preferred when handling files because different file formats can be handled this way and because DataView
s also handle the endianness of files from different architectures.
A task like this one can be handled by typed arrays, as in @le_m's answer, or by DataView
s - however, DataView
s can handle both endianness (if files are transferred over network from different CPUs) issues and different file formats (e.g. PDF files, which have some byte headers before the main content).