13

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?

2
  • 1
    XMLHttpRequest.responseType "arrayBuffer" is not supported. in Chrome. Commented Dec 3, 2012 at 18:43
  • This question may help others: stackoverflow.com/questions/6965107/… Commented Mar 2, 2016 at 20:31

2 Answers 2

13

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:

  • The first is about creating a view.
  • The second offsetting bytes.

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 );
}
0
11
function load_binary_resource(url) {
  var byteArray = [];
  var req = new XMLHttpRequest();
  req.open('GET', url, false);
  req.overrideMimeType('text\/plain; charset=x-user-defined');
  req.send(null);
  if (req.status != 200) return byteArray;
  for (var i = 0; i < req.responseText.length; ++i) {
    byteArray.push(req.responseText.charCodeAt(i) & 0xff)
  }
  return byteArray;
}

See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data for more details

1
  • Thank you for posting. Your code fixed my problem beautifully. I was trying to use strings before this, found bugs. Then I switched to blob. Felt like that was the wrong direction. This code is definitely the best solution. Commented Aug 31, 2020 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.