如何将4个字节转换为Swift浮点数?

时间:2014-06-23 06:05:06

标签: swift swift-playground

我正在Swift中编写一个MsgPack解析器来学习该语言。它感觉不太适合这项任务,但我一直在取得进展。现在我遇到了一个块,我似乎无法说服它将4个字节转换成浮点数。

var bytes:Array<UInt8> = [0x9A, 0x99, 0x99, 0x41] //19.20000

var f:Float = 0

memccpy(&f, &bytes, 4, 4)

print(f)

我在操场上得到:

  

致命错误:无法解包Optional.None   游乐场执行失败:错误:执行被中断,原因:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)。

任何想法接下来要尝试什么?

2 个答案:

答案 0 :(得分:13)

&放在&bytes上。 bytes是一个数组。

    var bytes:Array<UInt8> = [0x9A, 0x99, 0x99, 0x41] //19.20000

    var f:Float = 0.0

    memccpy(&f, bytes, 4, 4) // as per OP. memcpy(&f, bytes, 4) preferred

    println ("f=\(f)")// f=19.2000007629395

更新Swift 3

memccpy似乎在Swift 3中不起作用。正如评论员所说,使用memcpy

import Foundation
var bytes:Array<UInt8> = [0x9A, 0x99, 0x99, 0x41] //19.20000

var f:Float = 0.0

/* Not in Swift 3
 memccpy(&f, bytes, 4, 4) // as per OP.

 print("f=\(f)")// f=19.2
 */

memcpy(&f, bytes, 4) /

print("f=\(f)")// f=19.2

答案 1 :(得分:2)

public func parseInt32(bytes:[UInt8], offset:Int)->Int32{

    var pointer = UnsafePointer<UInt8>(bytes)
    pointer = pointer.advancedBy(offset)

    let iPointer =  UnsafePointer<Int32>(pointer)
    return iPointer.memory

}

public func parseFloat32(bytes:[UInt8], offset:Int)->Float32{
    var pointer = UnsafePointer<UInt8>(bytes)
    pointer = pointer.advancedBy(offset)

    let fPointer =  UnsafePointer<Float32>(pointer)
    return fPointer.memory

}