4

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:

Original HEX

Saved file:

Saved file

rvandoni
  • 3,297
  • 4
  • 32
  • 46
  • 1
    `I trasformed the hex string in an array of integers` - this unshown piece of "code" is where you most likely made a mistake or two – Jaromanda X Aug 05 '15 at 09:03
  • I don't think so, if I print the str into the console I can see the right values. By the way I will modify my question adding that part too! – rvandoni Aug 05 '15 at 09:06
  • you start with 684 "chars" in a "file" ... and end up with a string length 512 ... this happens BEFORE the code you posted - I'm sticking with my assumption that A problem exists in your "hex values" to "bytes" conversion – Jaromanda X Aug 05 '15 at 09:09
  • I have: 512 pairs of hex values -> 512 integers -> 512 chars -> I save the file -> 684 chars inside the file – rvandoni Aug 05 '15 at 09:11
  • 1
    I misunderstood which number meant what and which were correct and which were wrong - sorry – Jaromanda X Aug 05 '15 at 09:14
  • no problem Jaromanda X! – rvandoni Aug 05 '15 at 09:15
  • 2
    @rikpg can you just open file and compare contents with your hex stuff? This might give you a clue. – Andrey Aug 05 '15 at 09:45
  • @Andrey I added the hex files! – rvandoni Aug 05 '15 at 10:03
  • 1
    @rikpg that explains all. You are writing binary file as text. It converts bytes into chars in UTF8. C0 in latin1 is C3 80 in UTF8. Use binary mode where you save the file. – Andrey Aug 05 '15 at 10:07
  • thanks @Andrey!! I found a solution in two minutes thanks to you :) I'll add an answer... – rvandoni Aug 05 '15 at 10:23

1 Answers1

7

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");
rvandoni
  • 3,297
  • 4
  • 32
  • 46