我如何读取二进制数据,在Javascript中的字节数组? [英] How do I read binary data to a byte array in Javascript?
问题描述
我想读在JavaScript中的二进制文件将通过XMLHtt prequest可以得到,并能操作这些数据。从我的研发,我发现读一个二进制文件的数据这个方法到一个数组
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
设置页。
这里将出现在code到Uint8Array转换成字符串。作者给出的方法2:
Click on javascript
tab.
There will appear the code to convert the Uint8Array in a string. The author shows 2 method:
- 第一个是关于创建视图。
- 第二个字节偏移
编辑:报code完整性
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中的字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!