admin管理员组

文章数量:1334342

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

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

Share Improve this question asked Apr 17, 2014 at 22:39 user3547029user3547029 211 silver badge2 bronze badges 1
  • You're assuming that 1 character = 1 byte, which is not always true in Unicode. Just skip String all together – Paul S. Commented Apr 17, 2014 at 22:43
Add a ment  | 

1 Answer 1

Reset to default 8

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

本文标签: File APIHEX conversionJavascriptStack Overflow