title: Converting non-unicode binary strings to byte array in Javascript
body: <p>I read a binary file using ajax from a web server. The HTTP response is of contentType: 'application/octet-stream' and contains a binary string that is just a string of bytes (not unicode), for example (in hex):</p>
  
  <p>0x00 0x08 0x17 0xA1 0x01</p>
  
  <p>Note: in C this would be represented as 5 bytes in memory:</p>
  
  <pre><code>char buf[5] = {0, 8, 23, 161, 1}
  </code></pre>
  
  <p>...but in Javascript that is a string which ASCII representation is something like "   � " (I can't actually paste it properly as not all characters have a printable representation).</p>
  
  <p>I now need to convert this into an array of characters or integers so that I can access the numerical value of each character in the string. However iterating through the example string using the charCodeAt() function returns:</p>
  
  <pre><code>[0] 0
  [1] 8
  [2] 23
  [3] 65533
  [4] 1
  </code></pre>
  
  <p>because charCodeAt() decodes unicode characters, and 0xA1 is not recognised as valid unicode character so a <a href="http://www.fileformat.info/info/unicode/char/0fffd/index.htm" rel="nofollow noreferrer">Replacement Character</a> (65533) is used instead.</p>
  
  <p>I would like to get the following:</p>
  
  <pre><code>[0] 0
  [1] 8
  [2] 23
  [3] 161
  [4] 1
  </code></pre>
  
  <p>How to achieve this?</p>
  
  <p>Here is the code snippet:</p>
  
  <pre><code>$.ajax({
  url: url,
  type: "get",
  success: function(data) { // data contains binary representation of 0x00 0x08 0x17 0xA1 0x01
      var byteTab = []
      for (var n = 0; n &lt; data.length; ++n) {
          byteTab.push(data.charCodeAt(n))
      }
  })
  </code></pre>