get float value from nsdata objective-c iOS

↘锁芯ラ 提交于 2019-12-10 22:58:49

问题


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;


来源:https://stackoverflow.com/questions/18437535/get-float-value-from-nsdata-objective-c-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!