开发者

Converting floats to NSData and back in Objective-C

开发者 https://www.devze.com 2022-12-20 22:22 出处:网络
In an iphone application, I\'m looking to convert a float to NSData for it to be sent over bluetooth and then converted back again when it\'s received. I have the blueto开发者_C百科oth part working fi

In an iphone application, I'm looking to convert a float to NSData for it to be sent over bluetooth and then converted back again when it's received. I have the blueto开发者_C百科oth part working fine, but when I use this to convert to NSData:

NSData *data = [[NSData alloc]init];

float z = 9.8574; // Get the float value, 9.8574 is just an example

[data getBytes:&z length:sizeof(float)];

I can not convert it back to a float. I've tried a couple of methods but I'm wondering if this is the correct way to encode the float to NSData??

Thanks


Here is how to encode and decode a float with NSData:

encoding:

NSMutableData * data = [NSMutableData dataWithCapacity:0];
float z = ...;
[data appendBytes:&z length:sizeof(float)];

decoding:

NSData * data = ...; // loaded from bluetooth
float z;
[data getBytes:&z length:sizeof(float)];

A couple of things to note here:

1. You have to use NSMutableData if you are going to add things to the data object after creating it. The other option is to simply load the data all in one shot:

NSData * data = [NSData dataWithBytes:&z length:sizeof(float)];

2. the getBytes:length: method is for retrieving bytes from an NSData object, not for copying bytes into it.

0

精彩评论

暂无评论...
验证码 换一张
取 消