title: Decoding UTF-16 with PHP
body: <p>I have stumbled upon an interesting piece of code written in Python:</p>
  
  <pre><code>from struct import pack
  
  chars = [109, 0, 97, 0, 110, 0, 105, 0, 102, 0, 101, 0, 115, 0, 116, 0]
  length = 16
  
  data = ""
  for i in range(0, length):
      ch = pack("=b", chars[i])
      data += unicode(ch, errors='ignore')
  
      if data[-2:] == "\x00\x00":
          break
  
  end = data.find("\x00\x00")
  if end != -1:
      data = data[:end]
  
  print(len(data.decode("utf-16", "replace"))) // outputs 8, string is 'manifest'
  </code></pre>
  
  <p>As you can see, Python does decode <code>utf-16</code> properly.
  However, when I try to port the code to PHP I get bad results:</p>
  
  <pre><code>$chars = array(109, 0, 97, 0, 110, 0, 105, 0, 102, 0, 101, 0, 115, 0, 116, 0);
  $length = 16;
  
  $data = "";
  for ($i = 0; $i &lt; $length; $i++) {
      $data .= pack("c", $chars[$i]);
  
      if (substr($data, -2) == "\x00\x00") {
          break;
      }
  }
  
  $end = strpos($data, "\x00\x00");
  if ($end !== false) {
      $data = substr($data, 0, $end);
  }
  
  // md_convert_encoding() doesn't seem to work
  printf(strlen($data)); // outputs 16
  </code></pre>
  
  <p>The only solution I see is to just give up on the UTF magic and change the loop to:</p>
  
  <pre><code>for ($i = 0; $i &lt; $length; $i+=2)
  </code></pre>
  
  <p>Is there anything I can do about this, or just use the modified for loop?</p>
  
  <p>Thank you.</p>