微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift中的浮点十六进制表示法

我不明白浮点数是如何用 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-format非常相似(例如,请参阅
http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html).
它可以用于直接在其中指定浮点数
二进制IEEE 754表示,见Why does Swift use base 2 for the exponent of hexadecimal floating point values?欲获得更多信息.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐