从 nsdata Objective-c iOS 获取浮点值 [英] get float value from nsdata objective-c iOS
问题描述
我试图从包含多个十六进制值的 NSData
对象中获取浮点值.例如欧共体 51 38 41从这个 4 字节值我想得到浮点值 11.52.我必须如何在 xcode 中执行此操作?
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?
我用 NSScanner
(scanFloat, scanHexFloat)、NSNumberformatter
和 NSNumber
尝试过,我创建了一个字节数组并尝试了 float myFloat = *(float*)&myByteArray
.我在 stackoverflow 上找到了所有这些选项.
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.
我在 Windows 中用 C# 测试过,没有问题:
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);
有谁知道我必须如何在 xcode 中做到这一点???
Does anybody know how i have to do this in xcode???
谢谢,本杰明
推荐答案
从外部协议转换二进制数据时,请始终确保包含正确的字节序交换:
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);
您必须知道编码数据的字节序.您可能需要改用 CFSwapInt32LittleToHost
.
You have to know the endianness of the encoded data. You might need to use CFSwapInt32LittleToHost
instead.
这篇关于从 nsdata Objective-c iOS 获取浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!