title: Extract and convert NSData value from Bluetooth reading in Swift
body: <p>I am trying to read values from a Bluetooth 4.0 LE scale on iOS. How do I convert the Bluetooth Characteristics measurements received as <em>NSData</em> to dedicated Swift objects?</p>
  
  <p>As a specification I know that … </p>
  
  <p><strong>Bit 0 to Bit 12</strong> → weight (0 to 5000 g)</p>
  
  <p><strong>Bit 15</strong> → positive/negative weight value</p>
  
  <pre><code>func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
  
      let value:NSData = characteristic.value
  
      let weight:Double = … ?
      let negative:Bool = … ?
  </code></pre>
  
  <p>one more piece of information – looking at </p>
  
  <pre><code>value.length
  </code></pre>
  
  <p>it looks like I am always getting 1 or 2 bytes (?) of data from the device. However I am still not sure how to extract the data/values I was looking for. I'd appreciate any advice.</p>
  
  <p>Here's what works <em>a little bit</em> so far …</p>
  
  <pre><code>    var bin16:UInt16 = 0
      characteristic.value.getBytes(&amp;bin16, range: NSRange(location: 0,length: 1))
  
      println("Bytes \(characteristic.value.bytes) Length \(characteristic.value.length)")
      println("Value \(bin16)")
  </code></pre>
  
  <p>– Doing this I manage to get some weight reading. It seems to work unless the value is bigger than 255 or negative. Here are some examples:</p>
  
  <p><strong>75 grammes</strong></p>
  
  <p>Bytes 0x1655e458 Length 1 
  Value 75</p>
  
  <p><strong>367 grammes</strong> </p>
  
  <p>Bytes 0x1765cbc8 Length 2
  Value 161</p>
  
  <p><strong>-6 grammes</strong></p>
  
  <p>Bytes 0x17670f18 Length 2
  Value 32</p>
  
  <p>Also this gets transmitted more often in between – it doesn't stand for 160 gramme in this case. Maybe some sort of error code?!</p>
  
  <p>Bytes 0x146528b8 Length 2
  Value 160</p>