get float value from nsdata objective-c iOS

2019-07-20 19:19发布

问题:

I am trying to get a float value from a NSData object which contains several hex values. e.g. EC 51 38 41 From this 4 Byte values i want to get the float value 11.52. How do i have to do this in xcode?

I have tried it with NSScanner (scanFloat, scanHexFloat), NSNumberformatter and NSNumber, i created an Byte Array and tried float myFloat = *(float*)&myByteArray. All these Options i found here at stackoverflow.

I tested it in Windows with C# and there it was no problem:

byte[] bytes = new byte[4] { 0xEC, 0x51, 0x38, 0x41 };

float myFloat = System.BitConverter.ToSingle(bytes, 0);

Does anybody know how i have to do this in xcode???

Thanks, Benjamin

回答1:

When converting binary data from a foreign protocol always make sure to include proper swapping for endianness:

uint32_t hostData = CFSwapInt32BigToHost(*(const uint32_t *)[data bytes]);
float value = *(float *)(&hostData);

You have to know the endianness of the encoded data. You might need to use CFSwapInt32LittleToHost instead.



回答2:

NSData * data = ...; // loaded from bluetooth
float z;
[data getBytes:&z length:sizeof(float)];

Try this.



回答3:

I have tries it with NSScanner (scanFloat, scanHexFloat), NSNumberformatter and NSNumber

You're barking up the wrong tree here. NSScanner is for scanning strings. NSNumber is not the same as NSData, and NSNumberFormatter won't work with NSData either.

NSData is a container for plain old binary data. You've apparently got a float stored in an NSData instance; if you want to access it, you'll need to get the data's bytes and then interpret those bytes however you like, e.g. by casting to float:

float *p = (float*)[myData bytes];   // -bytes returns a void* that points to the data
float f = *p;