title: Javascript: how to convert hex data to binary and write it into a file
body: <p>I have a bunch of hex values and I have to convert it into binary data before write them into a file.</p>
  
  <p>I trasformed the hex string in an array of integers, then I convert each integer to a char:</p>
  
  <pre><code>// bytes contains the integers
  str = String.fromCharCode.apply(String, bytes);
  </code></pre>
  
  <p>now I create the blob file and download it:</p>
  
  <pre><code>var blob = new Blob([str], {type: "application/octet-stream"});
  saveAs(blob, "file.bin");
  </code></pre>
  
  <p>but something goes wrong: if I print the <code>length</code> of <code>bytes</code> and the length of <code>str</code> I have the same value (<code>512</code>), but the file contains 684 chars, and of course it isn't how I expect it.</p>
  
  <p>So I have:</p>
  
  <p><strong>512</strong> pairs of hex values ->
  <strong>512</strong> integers ->
  <strong>512</strong> chars ->
  I save the file ->
  <strong>684</strong> chars inside the file. </p>
  
  <p>What am I doing wrong? I even tried to add the charset to the blob file, ie:</p>
  
  <pre><code>var blob = new Blob([str], {type: "application/octet-stream;charset=UTF-8,"});
  </code></pre>
  
  <p>but with no success.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Original HEX:</p>
  
  <p><a href="https://i.stack.imgur.com/o8vJb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o8vJb.png" alt="Original HEX"></a></p>
  
  <p>Saved file:</p>
  
  <p><a href="https://i.stack.imgur.com/13TfX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/13TfX.png" alt="Saved file"></a></p>