将浮点数转换为NSData并返回Objective-C [英] Converting floats to NSData and back in Objective-C
问题描述
在iphone应用程序中,我希望将浮动转换为NSData,以便通过蓝牙发送,然后在收到时再转换回来。我有蓝牙部分工作正常,但当我使用它转换为NSData:
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)];
我无法将其转换回浮动。我已经尝试了几种方法,但我想知道这是否是将float编码为NSData的正确方法?
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??
谢谢
推荐答案
以下是如何使用 NSData编码和解码
: float
Here is how to encode and decode a float
with NSData
:
编码:
NSMutableData * data = [NSMutableData dataWithCapacity:0];
float z = ...;
[data appendBytes:&z length:sizeof(float)];
解码:
NSData * data = ...; // loaded from bluetooth
float z;
[data getBytes:&z length:sizeof(float)];
这里有几点需要注意:
1. 如果要在创建数据对象后向数据对象添加内容,则必须使用 NSMutableData
。另一种选择是简单地一次性加载数据:
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。 getBytes:length:
方法是从 NSData
对象中检索字节,而不是将字节复制到其中。
2. the getBytes:length:
method is for retrieving bytes from an NSData
object, not for copying bytes into it.
这篇关于将浮点数转换为NSData并返回Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!