问题
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