title: Interpreting Sphero 16-bit values (such as in Collisions)
body: <p>I'm using <a href="http://cylonjs.com/" rel="nofollow">Cylon.js</a> and Node.js to work with a Sphero, and I'm not sure how I am supposed to reconstruct the 16 bit values from the data returned from a collision event.</p>
  
  <p>The docs imply that they should be signed 16-bit integers, and that the numbers come in (MSB, LSB) byte order, but I get oddball values when I attempt to convert two bytes into what should be negative power ratings (such as impacts from behind or from the left).</p>
  
  <p>The Javascript code I am using to convert a two-btye Sphero value is this:</p>
  
  <pre><code>  function convertToSignedInt(msb, lsb) {
      var negative = msb &gt; 128;
      if (negative) {
        msb -= 128;
      }
      var value = msb*256 + lsb;
      if (negative) {
        value = 0 - value;
      }
      return value;
    }
  </code></pre>
  
  <p>Given raw collision data like the following:</p>
  
  <pre><code>{"SOP1":255,"SOP2":254,"ID_CODE":7,"DLEN":17,"DATA":[18,31,255,104,0,0,1,0,67,0,6,0,0,9,1,95],"CHK":156}
  </code></pre>
  
  <p>I then attempt to convert the DATA property to a more readable object using this:</p>
  
  <pre><code>  function convertCollisionData(data) {
      var obj = {};
      obj.xPower = convertToSignedInt(data[0], data[1]);
      obj.yPower = convertToSignedInt(data[2], data[3]);
      obj.zPower = convertToSignedInt(data[4], data[5]);
      obj.impactAxis = data[6];
      obj.xImpact = convertToSignedInt(data[7], data[8]);
      obj.yImpact = convertToSignedInt(data[9], data[10]);
      obj.speed = data[11];
  
      return obj;
    }
  </code></pre>
  
  <p>To come up with this:</p>
  
  <pre><code>{"xPower":4639,"yPower":-32616,"zPower":0
      ,"impactAxis":1,"xImpact":67,"yImpact":6,"speed":0}
  </code></pre>
  
  <p>It's obvious that the yPower is completely wrong, since this was a right-side (positive X) collision.  Since the xImpact and yImpact values are positive, they appear to be converting correctly.</p>
  
  <p>So the short version of the question is, <strong>what is the proper way to convert the two bytes to a signed integer?</strong></p>