Benny33
Benny33

Reputation: 505

Convert half precision float (bytes) to float in Swift

I would like to be able to read in half floats from a binary file and convert them to a float in Swift. I've looked at several conversions from other languages such as Java and C#, however I have not been able to get the correct value corresponding to the half float. If anyone could help me with an implementation I would appreciate it. A conversion from Float to Half Float would also be extremely helpful. Here's an implementation I attempted to convert from this Java 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)
}

Upvotes: 4

Views: 1905

Answers (1)

Stephen Canon
Stephen Canon

Reputation: 106117

If you have an array of half-precision data, you can convert all of it to float at once using vImageConvert_Planar16FtoPlanarF, which is provided by Accelerate.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]

You can also use this method to convert individual values, but it's fairly heavyweight if that's all that you're doing; on the other hand it's extremely efficient if you have large buffers of values to convert.

If you need to convert isolated values, you might put something like the following C function in your bridging header and use it from Swift:

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

This will use hardware conversion instructions when you're compiling for targets that have them (armv7s, arm64, x86_64h), and call a reasonably good software conversion routine when compiling for targets that don't have hardware support.

addendum: going the other way

You can convert float to half-precision in pretty much the same way:

static inline storeAsF16(float value, uint16_t *pointer) { *(const __fp16 *)pointer = value; }

Or use the function vImageConvert_PlanarFtoPlanar16F.

Upvotes: 5

Related Questions