swift 中的 Float 的 4 个字节给出了意想不到的小结果

4 bytes to a Float in a swift gives an unexpectedly small result

我正在尝试从 Swift according to this answer 中的二进制流重建浮点数。据我所知,字节是正确的,但生成的浮点数不是。

func didReceive(data: NSData!) {
    var x:Float = 0

    var bytes:[UInt8] = [UInt8](count: 4, repeatedValue: 0)
    data.getBytes(&bytes, range: NSMakeRange(0, 4))
    memcpy(&x, bytes, 4)

    NSLog("x:%f bytes:[%d, %d, %d, %d]", x, bytes[0], bytes[1], bytes[2], bytes[3]);
}

此函数打印出以下内容:

x:0.000000 bytes:[25, 0, 0, 0]

当我在调试器中检查 x 时,它报告的值为:

0.0000000000000000000000000000000000000000000350324616

然而,字节 [25,0,0,0] 应该是十六进制 0x19000000,我认为 should translate to about 6.617.

我哪里错了。 Swift 浮点数不是 IEEE754 32 位浮点数吗?

您在小端平台上,因此您的数组相当于 32 位整数 0x00000019,作为 IEEE 单精度浮点数,它是 approximately 3.5 * 10-44

仔细检查 page you linked to。它显示 0x19000000 转换为 6.617…E-24.

从另一个方向来看,你可以得到这样的 6.617 的十六进制模式:

String(unsafeBitCast(6.617 as Float, UInt32.self), radix: 16)

这给你 0x40D3BE77.

顺便说一句,如果您想尝试一种没有 memcpy 的方法,这应该可行:

let bytes: [UInt8] = [0x40,0xD3,0xBE,0x77]

let f = bytes.reverse().withUnsafeBufferPointer {
    UnsafePointer<Float>([=11=].baseAddress).memory
}