简体   繁体   English

如何使用Swift从Metal纹理中读取半精度浮点数?

[英]How do I read half precision floating point numbers from a Metal texture with Swift?

My Metal compute kernel writes to a texture with format MTLPixelFormat.RG16Float, half precision floating point numbers. My Metal计算内核写入格式为MTLPixelFormat.RG16Float的纹理,半精度浮点数。 This is because Metal does not support writing to 32 bits floating point textures. 这是因为Metal不支持写入32位浮点纹理。

I need to read these half precision numbers in my swift program? 我需要在我的swift程序中读取这些半精度数字吗? I have moved the texture into a Swift UInt8 array, but I cannot figure out how to convert the half precision floats into Swift floats. 我已将纹理移动到Swift UInt8数组中,但我无法弄清楚如何将半精度浮点数转换为Swift浮点数。

EDIT: the below answer was written for Swift v1. 编辑:下面的答案是为Swift v1编写的。 Later versions of Swift added support via the float16_t type. 更高版本的Swift通过float16_t类型添加了支持。 Manual conversion may still be useful in some cases. 在某些情况下,手动转换可能仍然有用。


There is no built in method to interpret halfs as floats, you have to convert it yourself. 没有内置的方法将halfs解释为浮点数,你必须自己转换它。 The half datatype is a floating point format following IEEE 754. You can read the values in your swift program using UInt16 and then convert from this to a float value. 半数据类型是IEEE 754之后的浮点格式。您可以使用UInt16读取swift程序中的值,然后将其转换为浮点值。 I don't know of any conversion routines written in Swift, but here are two libraries written in C++ that could be converted easily enough: 我不知道用Swift编写的任何转换例程,但这里有两个用C ++编写的库,可以很容易地转换:

http://mrob.com/pub/math/s10e5.h.txt http://mrob.com/pub/math/s10e5.h.txt

http://half.sourceforge.net/ http://half.sourceforge.net/

In the first library it is the function operator float() that you need to convert, that takes the UInt16 member variable _h and outputs a float. 在第一个库中,它是您需要转换的函数operator float(),它接受UInt16成员变量_h并输出一个浮点数。

Actually @Muzza's answer is not correct. 实际上@ Muzza的答案是不正确的。 You could have read them from a float16_t pointer and cast them to a normal float32_t . 你可以从float16_t指针读取它们并将它们转换为普通的float32_t No need to use external libraries. 无需使用外部库。 Just import the arm_neon header. 只需导入arm_neon标头即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM