I have a bunch of hex values and I have to convert it into binary data before write them into a file.
I trasformed the hex string in an array of integers, then I convert each integer to a char:
// bytes contains the integers
str = String.fromCharCode.apply(String, bytes);
now I create the blob file and download it:
var blob = new Blob([str], {type: "application/octet-stream"});
saveAs(blob, "file.bin");
but something goes wrong: if I print the length
of bytes
and the length of str
I have the same value (512
), but the file contains 684 chars, and of course it isn't how I expect it.
So I have:
512 pairs of hex values -> 512 integers -> 512 chars -> I save the file -> 684 chars inside the file.
What am I doing wrong? I even tried to add the charset to the blob file, ie:
var blob = new Blob([str], {type: "application/octet-stream;charset=UTF-8,"});
but with no success.
EDIT:
Original HEX:
Saved file:
Thanks to Andrey I found the solution:
I have to write in binary mode, so:
var ab = new ArrayBuffer(bytes.length); //bytes is the array with the integer
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes[i];
}
var blob = new Blob([ia], {type: "application/octet-stream"});
saveAs(blob, id + "_<?php echo $report['md5']; ?>.bin");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With