Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting uint8_t and uint16_t to NSMutableData

Tags:

c

ios

objective-c

I am fairly new to programming and I am trying to develop a bluetooth fitness device using CoreBluetooth for iOS. I bought a bunch of different devices from different hardware manufacturers for testing and one of the instructions for sending values to the device

I want to be able to write a value (fitness goal) to the Bluetooth fitness device. I know how to read/write with Bluetooth.

I just don't know how to convert the values I want to uint8_t and uint16_t and then combine it into an 8 byte NSMutableData.

Can anyone tell me how I would do this?

like image 248
Teddy13 Avatar asked Feb 13 '23 12:02

Teddy13


1 Answers

The first thing to worry about is byte ordering. It doesn't matter for the uint8_t but it matters for anything larger. You can have big-endian or little-endian. Check the docs for device.

Start with your values:

uint8_t days = 12;
uint16_t walked = 225;
uint16_t ran = 110
uint16_t steps = 750;
uint8_t users = 2;

NSMutableData *data = [NSMutableData data];
[data appendBytes:&days length:1];
uint16_t network = CFSwapInt16HostToBig(walked);
[data appendBytes:&network length:2];
network = CFSwapInt16HostToBig(ran);
[data appendBytes:&network length:2];
network = CFSwapInt16HostToBig(steps);
[data appendBytes:&network length:2];
[data appendBytes:&users length:1];

The above assumes you need the data in big-endian format. If it need to be little-endian then change CFSwapInt16HostToBig to CFSwapInt16HostToLittle.

like image 136
rmaddy Avatar answered Feb 15 '23 11:02

rmaddy