File API - HEX conversion - Javascript

2019-09-12 12:28发布

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.

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)?

Many thanks,

Jerome

1条回答
虎瘦雄心在
2楼-- · 2019-09-12 13:15

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);
查看更多
登录 后发表回答