title: Create hex-representation of signed int in PHP
body: <p>I'm parsing a binary and stumbled upon some 16bit (2 byte) values that I need to convert from hex to dec and vice versa.
  Positive values look like this "0075" (117) while negative ones look like that "FE75" (-395).</p>
  
  <p>I'm using this function to convert from hex to signed int, which works, but I can't seem to find a solution for signed int to hex-representation.</p>
  
  <pre><code>function hexdecs($hex)
  {
      // ignore non hex characters
      $hex = preg_replace('/[^0-9A-Fa-f]/', '', $hex);
  
      // converted decimal value:
      $dec = hexdec($hex);
  
      // maximum decimal value based on length of hex + 1:
      //   number of bits in hex number is 8 bits for each 2 hex -&gt; max = 2^n
      //   use 'pow(2,n)' since '1 &lt;&lt; n' is only for integers and therefore limited to integer size.
      $max = pow(2, 4 * (strlen($hex) + (strlen($hex) % 2)));
  
      // complement = maximum - converted hex:
      $_dec = $max - $dec;
  
      // if dec value is larger than its complement we have a negative value (first bit is set)
      return $dec &gt; $_dec ? -$_dec : $dec;
  }
  </code></pre>