Swift:从字节数据中提取浮点数 [英] Swift: extract float from byte data

查看:156
本文介绍了Swift:从字节数据中提取浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种健壮且优雅的方法来从数组中提取四个大端字节作为Float.

I'm looking for a robust and elegant way to extract four big-endian bytes from an array as a Float.

我可以通过如下方式获得带有这些位的UInt32:

I can get a UInt32 with the bits via something like this:

let data: [Byte] = [0x00, 0x00, 0x00, 0x40, 0x86, 0x66, 0x66, 0x00]
let dataPtr = UnsafePointer<Byte>(data)
let byteOffset = 3
let bits = UnsafePointer<UInt32>(dataPtr + byteOffset)[0].bigEndian

但是我找不到在Swift中将其转换为Float的好方法.

But I can't figure out a good way to convert this into a Float in Swift.

例如,在Java中:

float f = Float.intBitsToFloat(bits)

或在C中:

float f = *(float *)&bits;

我尝试将dataPtr强制转换为浮点数UnsafePointer,但是字节序是个问题.

I tried casting the dataPtr to a float UnsafePointer, but then the endianness is a problem.

有什么建议吗?

推荐答案

浮点类型具有静态的_fromBitPattern,它将返回一个值. <Type>._BitsType是正确大小的无符号整数的类型别名:

The floating point types have a static _fromBitPattern that will return a value. <Type>._BitsType is a type alias to the correctly sized unsigned integer:

let data: [Byte] = [0x00, 0x00, 0x00, 0x40, 0x86, 0x66, 0x66, 0x00]
let dataPtr = UnsafePointer<Byte>(data)
let byteOffset = 3
let bits = UnsafePointer<Float._BitsType>(dataPtr + byteOffset)[0].bigEndian
let f = Float._fromBitPattern(bits)

您不会在自动完成中看到该方法,但它是FloatingPointType的一部分协议.有一个实例方法可以将这些位还给您,称为._toBitPattern().

You don't see that method in auto-completion, but it's a part of the FloatingPointType protocol. There's an instance method that will give you back the bits, called ._toBitPattern().

这篇关于Swift:从字节数据中提取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆