title: Bluetooth heartrate monitor byte decoding
body: <h1>Problem :</h1>
  
  <p>I am having trouble with understanding the returned data of the <a href="https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml" rel="nofollow">BLE Heart Rate Characteristic</a>(service <code>180d</code>, characteristic <code>2a37</code>).</p>
  
  <p>According to the specification there will be either 6 or 7 bytes of data (when base64-decoded), i fully understand how to deal with it when this is the case.</p>
  
  <p>But sometimes it won't return 6 or 7 bytes but 8 and more rarely 4 bytes, i have no idea why there are more/less bytes and what the meaning of the added bytes is or which bytes are left out.</p>
  
  <p>I could skip all the cases where there are not 6 or 7 bytes but i want to fully understand this.</p>
  
  <p>I am <em>certain</em> that the converting the base64-encoded to byte-array is done correctly, i made a function for it <strong>and</strong> checked it using manual base64-decode combined with <code>charCodeAt(index)</code> <strong>and</strong> truly manually checked it using good ol' pencil, paper and brain (not necessarily in that order).</p>
  
  <h3>TL;DR :</h3>
  
  <p>BLE Heart Rate (<code>180d</code>,<code>2a37</code>) sometimes does not return the expected amount of bytes (4 and 8 when it should be either 6 or 7 bytes).
  <strong>What exactly happened and why?</strong></p>
  
  <h2>Example :</h2>
  
  <pre><code>// Example results in byte-array's
  ["00010110", "01110111", "00000100", "00000010"] // unexpected 4 byte
  ["00010110", "01111000", "11111111", "00000001", "11111111", "00000001", "00001100", "00000001"] // unexpected 8 byte
  ["00010110", "01110111", "00001000", "00000010", "00001000", "00000010"] // normal 6 byte
  
  // Example results in hex-array's (easier to read on small screens)
  ["0x16","0x77","0x04","0x02"] // unexpected 4 byte
  ["0x16","0x78","0xFF","0x01","0xFF","0x01","0x0C","0x01"] // unexpected 8 byte
  ["0x16","0x77","0x08","0x02","0x08","0x02"] // normal 6 byte
  </code></pre>
  
  <h3>Byte Explanation :</h3>
  
  <ol>
  <li>Flags. The first bit (most right) is on if the heart rate is in 16 bit format (i only got 8 bit).</li>
  <li>heartrate, if the heart rate is in 16 bit format there will be 2 bytes here</li>
  <li>energy expended</li>
  <li>energy expended</li>
  <li>rr interval</li>
  <li>rr interval</li>
  </ol>