文件 API - 十六进制转换 - Javascript [英] File API - HEX conversion - Javascript

查看:23
本文介绍了文件 API - 十六进制转换 - Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试借助 File API 读取本地文本文件,并使用类似于bin2hex()"的函数(使用 CharCodeAt() 函数)将其转换为 HEX 文件,然后最后处理十六进制数字以获得我的结果.所有这些都在 Javascript 中.

I am trying to read a local text file with the help of the File API, and convert it to an HEX file using a similar function to "bin2hex()" (using CharCodeAt() function), and then finally process the HEX numbers to obtain my results. All this in Javascript.

要将我的文件转换为 HEX 数组,我通过 for 循环文件扫描文件的每个字符,然后使用 bin2hex() 函数获取 HEX 值.我希望在 0x00 和 0xFF 之间的结果对应于我尝试转换的任何字符.但似乎有时我会无缘无故地获得 0xfffd 或 0x00.您可以通过 charcodeat() 函数处理哪些字符或使用 File API 读取哪些字符有限制吗?或者是否有更简单的方法(PHP、Ajax)?

To convert my file to an HEX array, I scan each character of the file via a for loop file and then use the bin2hex() function to obtain the HEX value. I would expect a result between 0x00 and 0xFF corresponding to whatever character I am trying to convert. But It seems that sometimes I am obtaining 0xfffd or 0x00 for no apparent reasons. Is there a limitations in terms of which characters you can process through the charcodeat() function or read with the File API? Or is there maybe easier way to do it (PHP, Ajax)?

非常感谢,

杰罗姆

推荐答案

直接进入 Bytes 而不是通过 String

Go straight into Bytes rather than via String

var file = new Blob(['hello world']); // your file

var fr = new FileReader();
fr.addEventListener('load', function () {
    var u = new Uint8Array(this.result),
        a = new Array(u.length),
        i = u.length;
    while (i--) // map to hex
        a[i] = (u[i] < 16 ? '0' : '') + u[i].toString(16);
    u = null; // free memory
    console.log(a); // work with this
});
fr.readAsArrayBuffer(file);

这篇关于文件 API - 十六进制转换 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆