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 中将二进制数据读取到字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Javascript 中将二进制数据读取到字节数组
基础教程推荐
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
