Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 348
NIKHIL Avatar asked Jul 15 '11 05:07

NIKHIL


2 Answers

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.

like image 57
Adam Rosenfield Avatar answered Oct 16 '22 20:10

Adam Rosenfield


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.

like image 23
EmptyStack Avatar answered Oct 16 '22 19:10

EmptyStack