2
let hexString = "0x42f9b6c9"
let toInt = Int32(truncatingBitPattern: strtoul(self, nil, 16))
let toFloat = Float(bitPattern: UInt32(self))

RESULT: 124.857

let hexString = "0xc2f9b6c9"
let toInt = Int32(truncatingBitPattern: strtoul(self, nil, 16))
let toFloat = Float(bitPattern: UInt32(self))

app crashes here because the value is negative, expected result is -124.857

Please help. Thank you!

user
  • 623
  • 6
  • 6

2 Answers2

2

strtoul means string to unsigned long. Try strtol

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
  • 3
    Also, the "U" in UInt32 stands for "unsigned". – creeperspeak Mar 15 '17 at 00:41
  • @creeperspeak, really? Sincerely, I always thought it meant Unicode. Learn something new every day. Thanks! (And yeah, now that I'm actually thinking, what's the difference between an Int that's Unicode or not. In fact, what *would* a unicode Int mean?) –  Mar 15 '17 at 00:51
  • Thank you :) But do you guys know how to convert it to signed? – user Mar 15 '17 at 01:27
  • @user You'll also need to say `UInt32(truncatingBitPattern: ...` instead of using `Int32`. – Hamish Mar 15 '17 at 10:11
0

Better to make an extension of String

extension String {
func hexToFloat() -> Float {
    var toInt = Int32(truncatingBitPattern: strtol(self, nil, 16))
    var float:Float32!
    memcpy(&float, &toInt, MemoryLayout.size(ofValue: float))
    print("\(float)")
    return float
}

}

Example

"0xc2f9b6c9".hexToFloat()
//-124.857
"0x41240000".hexToFloat()
//10.25
Kraming
  • 217
  • 3
  • 8