Home » Ios » i want to convert NSData To double value in Iphone

i want to convert NSData To double value in Iphone

Posted by: admin February 24, 2018 Leave a comment


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

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


double val = *double_ptr;