1

I currently have a function that intakes UInt16 and converts it into data to send over bluetooth.

Here is a snippet:

var integerToSend = UInt16(10)
let commandID = 0x07
let data = NSMutableData(bytes: &commandID, length: 1)
data.append(&integerToSend, length: 2)

I am now trying to write to a register that intakes 12 bit data. What would be the best way to comply with this format?

Geoffrey
  • 10,843
  • 3
  • 33
  • 46
riceman89
  • 179
  • 1
  • 13
  • 1
    12-bit integer is sort of packed form which does not align to byte boundaries. You need to show more details about the data format you want to use. – OOPer Aug 05 '17 at 02:02

1 Answers1

0

Obviously you will lose some precision doing this since the values are lower resolution, but the basic idea is to divide the value by the maximum, and scale it to the new maximum.

Max 16 bit = 65535
Max 12 bit = 4095
Out = Round(In / 65535 * 4095)

Alternatively if you don't care about the least significant bits you could just shift the value right by 4

Out = In >> 4
Geoffrey
  • 10,843
  • 3
  • 33
  • 46
  • Thanks for the response. Forgive me for my lack of understanding here, but it seems like I would lose a lot of precision...for example, if I try to convert "42" into 12 bit format, I'll end up with 2. – riceman89 Aug 04 '17 at 23:39
  • How else would you convert to 12 bit?. it's not a compatible format, you only have 12 bits to store a number instead of 16. You can only do one of two things here, scale or truncate. – Geoffrey Aug 04 '17 at 23:50