title: Writing Byte Array To Binary File Javascript
body: <p>I am trying to write a script that generates random numbers these number then are converted to groups of 4Bytes each then these 4-bytes-groups are put into an Uint8Array finally I try to save the array to binary file. Here is my code:</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Raandom Number Generator&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;script src="http://code.jquery.com/jquery-1.11.0.min.js"&gt;&lt;/script&gt;
  &lt;script src="filesaver.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
      $(function() {
          if (!Date.now) {
              Date.now = function() {
                  return new Date().getTime();
              };
          }
  
          alert("started");
          var currentMousePos = {
              x : -1,
              y : -1
          };
          var randomData = [];
          var bytes = new Int8Array(4);
  
          $(document).mousemove(function(event) {
  
              if(randomData.length&gt;=1231){
                  $(document).unbind('mousemove');
                  console.log("Finished generating numbers ... trying to save file");
                  randomData = new Uint8Array(randomData);
                  var blob = new Blob(randomData, {type: "application/octet-stream"});
                  saveAs(blob, "rand.bin");
                  return;
              }
              currentMousePos.x = event.pageX;
              currentMousePos.y = event.pageY;
              var longRandomNumber = Date.now() * (event.pageX + 1)
                      * (event.pageY + 1);
              for ( var i = 3; i &gt;= 0; i--) {
                  bytes[i] = longRandomNumber &amp; (255);
                  longRandomNumber = longRandomNumber &gt;&gt; 8
              }
              for ( var i = 0; i &lt; 4; i++) {
                  randomData.push(bytes[i]);
              }
              console.log(randomData.length);
          });
      })
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>The problem is that the generated file contains numbers <code>plain numbers</code> for example an element in the Uint8Array may be 65, in my understanding to binary this value should be saved as capital letter <strong>A</strong> but it is stored as <strong>65</strong> instead</p>
  
  <p><strong><em>Note</em></strong></p>
  
  <p>filesaver.min.js is a library that I use to save files from JS (<a href="https://github.com/eligrey/FileSaver.js/" rel="nofollow">Link on GitHub</a>)</p>