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

标签 swift hex

我不明白 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/

相关文章:

bash - 生成一定范围的十六进制数

ios - 无法将 ToFile 写入 NSSearchPathForDirectoriesInDomains(.CachesDirectory、.UserDomainMask、true)

ios - 如何更改 UITableView Swift 3 中的分隔符高度?

ios - UIView.transition动画它只工作一次,第二次图片消失

mysql - 如何在 MySQL 中取消十六进制并进行不区分大小写的搜索?

ios - 如何在 HMAC 中以 HEX Swift iOS 形式传递 key

javascript - 如何在 Swift 的 JavaScriptCore 中导入模块?

ios - NSDateFormatter 格式不正确

javascript - 如何在没有十六进制_id的情况下使用MongoDB find

c++ - 为什么 std::hex 和 std::oct 标志不起作用?