如何在Javascript中将二进制数据读取到字节数组?

dez*_*cus 9 javascript binary binary-data

我想读取JavaScript中的二进制文件,该文件将通过XMLHttpRequest获取并能够操作该数据.从我的研究中我发现了这种将二进制文件数据读入数组的方法

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);
};
Run Code Online (Sandbox Code Playgroud)

如何将此二进制数据数组转换为人类可读字符串?

use*_*064 8

我相信你会发现这有用:http://jsdo.it/tsmallfield/uint8array.

单击javascript选项卡.将出现用于将Uint8Array转换为字符串的代码.作者展示了2种方法:

  • 第一个是关于创建视图.
  • 第二个偏移字节.

编辑: 报告代码的完整性

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 );
}
Run Code Online (Sandbox Code Playgroud)


Phy*_*yxx 7

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;
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data