开发者

i want to convert NSData To double value in Iphone

i want covert content of NSData Which is actually i need as a double type how can i convert it?

here 开发者_开发知识库 1ff46c56 7dd86f40 nsdata byte and i want in double


Assuming your data is exactly 8 bytes, you can convert it to a double using memcpy(3):

double ConvertNSDataToDouble(NSData *data)
{
    double d;
    assert([data length] == sizeof(d));
    memcpy(&d, [data bytes], sizeof(d));
    return d;
}

Note that this assumes that the data is in native endian format. If you know that the data is big- or little-endian, then you may need to endian-swap the bytes first.


You can also do it like this (apart from Adam Rosenfield's answer). This will work only if the data is UTF8 encoded.

NSString *dbleStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
double dble = [dbleStr doubleValue];

If the data is in endian format use one of the respective encoding formats from NSUTF16BigEndianStringEncoding, NSUTF16LittleEndianStringEncoding.

Note: The data should contain a double value. Otherwise you will get unexpected results.


Solution with less overhead

const double *double_ptr = [data bytes];

Examples of use is simply:

double val = double_ptr[0]; // the first double value in array

or

double val = *double_ptr;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜