Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to convert hex data to binary and write it into a file

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

like image 234
rvandoni Avatar asked Mar 15 '23 04:03

rvandoni


1 Answers

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");
like image 153
rvandoni Avatar answered Apr 25 '23 20:04

rvandoni