0

I'm trying to reconstruct a float from a binary stream in Swift according to this answer. As far as I can tell, the bytes are correct, but the resulting float is not.

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]);
}

This function prints out the following:

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

When I inspect x in the debugger, it reports the value as:

0.0000000000000000000000000000000000000000000350324616

However, the bytes [25,0,0,0] should be hex 0x19000000, which I think should translate to about 6.617.

Where's my mistake here. Is a Swift float not a IEEE754 32 bit float?

Community
  • 1
  • 1
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • 1
    This looks kind of like an endianness issue, but I have no experience with Swift and am unable to really diagnose the problem. – user2357112 Mar 14 '15 at 23:49

2 Answers2

2

Double-check the page you linked to. It shows 0x19000000 translates to 6.617…E-24.

Coming at it from the other direction, you can get the hex pattern of 6.617 like this:

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

which gives you 0x40D3BE77.

BTW if you want to try a way to do it without the memcpy, this should work:

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

let f = bytes.reverse().withUnsafeBufferPointer {
    UnsafePointer<Float>($0.baseAddress).memory
}
Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
1

You are on a little-endian platform, so your array is equivalent to the 32-bit integer 0x00000019, which, as an IEEE single precision floating-point number, is approximately 3.5 * 10-44.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Interesting. So if I add a `bytes = bytes.reverse()` line in there, `x` becomes `0.0000000000000000000000066174449` which seems to have the right digits at least, but is still quite a few orders of magnitude off. – Alex Wayne Mar 14 '15 at 23:59
  • 1
    No, it's not any orders of magnitude off. The page you linked gives an answer of about 6.617 * 10^-24. That's what the "E-24" suffix means. – rob mayoff Mar 15 '15 at 00:45
  • Haha! Missed that. Thanks rob – Alex Wayne Mar 15 '15 at 00:46