Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

iphone - Converting floats to NSData and back in Objective-C

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 bluetooth 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...