I want to read a binary file in JavaScript that would be gotten through XMLHttpRequest and be able to manipulate that data. From my researching I discovered this method of reading a binary file data into an array
var xhr = new XMLHttpRequest();
xhr.open('GET', '/binary_And_Ascii_File.obj', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
};
How do I convert this binary data array to a human-readable-string?
Byte arrays mostly contain binary data such as an image. If the byte array that you are trying to convert to String contains binary data, then none of the text encodings (UTF_8 etc.) will work.
The ArrayBuffer is a data type that is used to represent a generic, fixed-length binary data buffer.
The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".
JavaScript can handle binary data via typed arrays. And here is a library for dealing with binary files, that you can use as a reference point for your application.
I'm sure you will find this helpful: http://jsdo.it/tsmallfield/uint8array.
Click on javascript
tab.
There will appear the code to convert the Uint8Array in a string. The author shows 2 method:
EDIT: report the code for completeness
var buffer = new ArrayBuffer( res.length ), // res is this.response in your case
view = new Uint8Array( buffer ),
len = view.length,
fromCharCode = String.fromCharCode,
i, s, str;
/**
* 1) 8bitの配列に入れて上位ビットけずる
*/
str = "";
for ( i = len; i--; ) {
view[i] = res[i].charCodeAt(0);
}
for ( i = 0; i < len; ++i ) {
str += fromCharCode( view[i] );
}
/**
* 2) & 0xff で上位ビットけずる
*/
str = "";
for ( i = 0; i < len; ++i ) {
str += fromCharCode( res[i].charCodeAt(0) & 0xff );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With