How do I read binary data to a byte array in Javascript?(如何在 Javascript 中将二进制数据读取到字节数组?)
问题描述
我想用 JavaScript 读取一个二进制文件,该文件将通过 XMLHttpRequest 获取并能够操作该数据.在我的研究中,我发现了这种将二进制文件数据读入数组的方法
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?
推荐答案
我相信你会发现这很有帮助:http://jsdo.it/tsmallfield/uint8array.
I'm sure you will find this helpful: http://jsdo.it/tsmallfield/uint8array.
点击 javascript
标签.将出现将 Uint8Array 转换为字符串的代码.作者展示了2种方法:
Click on javascript
tab.
There will appear the code to convert the Uint8Array in a string. The author shows 2 method:
- 首先是关于创建视图.
- 第二个偏移字节.
报告代码的完整性
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 );
}
这篇关于如何在 Javascript 中将二进制数据读取到字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!