我不明白 float 在 Swift 中是如何用十六进制表示法表示的。 Apple 的文档显示 0xC.3p0 等于十进制的 12.1875。有人可以指导我如何进行转换吗?我知道在十进制十六进制值 0xC = 12 之前。小数点后的 3p0 是我难倒的地方。
最佳答案
来自documentation :
Floating-Point Literals
...
Hexadecimal floating-point literals consist of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent. The hexadecimal fraction consists of a decimal point followed by a sequence of hexadecimal digits. The exponent consists of an upper- or lowercase p prefix followed by a sequence of decimal digits that indicates what power of 2 the value preceding the p is multiplied by. For example, 0xFp2 represents 15 × 22, which evaluates to 60. Similarly, 0xFp-2 represents 15 × 2-2, which evaluates to 3.75.
你的情况
0xC.3p0 = (12 + 3/16) * 2^0 = 12.1875
另一个例子:
0xAB.CDp4 = (10*16 + 11 + 12/16 + 13/16^2) * 2^4 = 2748.8125
此格式与 %a
printf 格式非常相似(参见示例
http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html ).
它可以用来直接在其指定一个 float
二进制 IEEE 754 表示,参见 Why does Swift use base 2 for the exponent of hexadecimal floating point values?
获取更多信息。
关于swift - Swift 中的浮点十六进制表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735081/