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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6994712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:11:43  来源:igfitidea点击:

How do I read binary data to a byte array in Javascript?

javascriptbinarybinary-data

提问by Zeeno

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

我想在 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);
};

How do I convert this binary data array to a human-readable-string?

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

采纳答案by user278064

I'm sure you will find this helpful: http://jsdo.it/tsmallfield/uint8array.

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

Click on javascripttab. There will appear the code to convert the Uint8Array in a string. The author shows 2 method:

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

  • 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 );
}

回答by Phyxx

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_Datafor more details

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