How do you convert a hex to signed float in Swift? Works fine with positive number but doesn't work on negative

北战南征 提交于 2019-12-11 07:55:58

问题


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!


回答1:


strtoul means string to unsigned long. Try strtol




回答2:


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


来源:https://stackoverflow.com/questions/42799129/how-do-you-convert-a-hex-to-signed-float-in-swift-works-fine-with-positive-numb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!