Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 4 bytes to a Swift float?

I'm writing a MsgPack parser in Swift as a way to learn the language. It doesn't feel very well suited to the task but I've been making progress. Now I've hit a block where I can't seem to convince it to convert 4 bytes into a float.

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

var f:Float = 0

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

print(f)

In the playground I get:

fatal error: Can't unwrap Optional.None Playground execution failed: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

Any ideas what to try next?

like image 879
Brian Avatar asked Jun 23 '14 06:06

Brian


1 Answers

Drop the & on &bytes. bytes is an array.

    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

Update Swift 3

memccpy does not seem to work in Swift 3. As commentators have said, use 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
like image 161
Grimxn Avatar answered Oct 16 '22 15:10

Grimxn