将半精度浮点数(字节)转换为 Swift 中的浮点数

Ben*_*y33 4 floating-point precision swift

我希望能够从二进制文件中读取半浮点数并将它们转换为 Swift 中的浮点数。我查看了其他语言(如 Java 和 C#)的几种转换,但是我无法获得与半浮点数相对应的正确值。如果有人可以帮助我实施,我将不胜感激。从浮动到半浮动的转换也将非常有帮助。这是我试图从这个Java implementation转换的implementation

    static func toFloat(value: UInt16) -> Float {
    let value = Int32(value)
    var mantissa = Int32(value) & 0x03ff
    var exp: Int32 = Int32(value) & 0x7c00
    if(exp == 0x7c00) {
        exp = 0x3fc00
    } else if exp != 0 {
        exp += 0x1c000
        if(mantissa == 0 && exp > 0x1c400) {
            return Float((value & 0x8000) << 16 | exp << 13 | 0x3ff)
        }
    } else if mantissa != 0 {
        exp = 0x1c400
        repeat {
            mantissa << 1
            exp -= 0x400

        } while ((mantissa & 0x400) == 0)
        mantissa &= 0x3ff
    }
    return Float((value & 0x80000) << 16 | (exp | mantissa) << 13)
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*non 5

如果您有一个半精度数据数组,您可以使用vImageConvert_Planar16FtoPlanarFAccelerate.framework 提供的将其全部转换为浮点数:

import Accelerate
let n = 2
var input: [UInt16] = [ 0x3c00, 0xbc00 ]
var output = [Float](count: n, repeatedValue: 0)
var src = vImage_Buffer(data:&input, height:1, width:UInt(n), rowBytes:2*n)
var dst = vImage_Buffer(data:&output, height:1, width:UInt(n), rowBytes:4*n)
vImageConvert_Planar16FtoPlanarF(&src, &dst, 0)
// output now contains [1.0, -1.0]
Run Code Online (Sandbox Code Playgroud)

您也可以使用此方法来转换单个值,但如果您只需要这样做,它就相当重量级;另一方面,如果您有大量要转换的值缓冲区,则效率非常高。

如果您需要转换孤立值,您可能会在桥接头中放置类似以下 C 函数的内容,并在 Swift 中使用它:

#include <stdint.h>
static inline float loadFromF16(const uint16_t *pointer) { return *(const __fp16 *)pointer; }
Run Code Online (Sandbox Code Playgroud)

当您编译具有硬件转换指令的目标(armv7s、arm64、x86_64h)时,这将使用硬件转换指令,并在编译没有硬件支持的目标时调用相当好的软件转换例程。

附录:走另一条路

您可以以几乎相同的方式将浮点数转换为半精度:

static inline storeAsF16(float value, uint16_t *pointer) { *(const __fp16 *)pointer = value; }
Run Code Online (Sandbox Code Playgroud)

或者使用函数vImageConvert_PlanarFtoPlanar16F