如何在Swift中读取Float或Double的原始字节?
How can I read the raw bytes of a Float or Double in Swift?
示例:
let x = Float(1.5) let bytes1: UInt32 = getRawBytes(x) let bytes2: UInt32 = 0b00111111110000000000000000000000我希望bytes1和bytes2包含相同的值,因为此二进制数是1.5的Float表示形式.
I want bytes1 and bytes2 to contain the same value, since this binary number is the Float representation of 1.5.
我需要它执行像&和>>这样的按位操作(这些未在浮点数上定义).
I need it to do bit-wise operations like & and >> (these are not defined on a float).
推荐答案针对Swift 3的更新:自Swift 3起,所有浮点类型 具有bitPattern属性,该属性返回带以下内容的无符号整数: 相同的内存表示形式,以及相应的init(bitPattern:) 反向转换的构造函数.
Update for Swift 3: As of Swift 3, all floating point types have bitPattern property which returns an unsigned integer with the same memory representation, and a corresponding init(bitPattern:) constructor for the opposite conversion.
示例: Float至UInt32:
let x = Float(1.5) let bytes1 = x.bitPattern print(String(format: "%#08x", bytes1)) // 0x3fc00000示例: UInt32至Float:
let bytes2 = UInt32(0x3fc00000) let y = Float(bitPattern: bytes2) print(y) // 1.5您可以用相同的方式在Double和UInt64之间进行转换, 或在CGFloat和UInt之间.
In the same way you can convert between Double and UInt64, or between CGFloat and UInt.
Swift 1.2 和 Swift 2 的旧答案Swift浮点类型具有_toBitPattern()方法:
let x = Float(1.5) let bytes1 = x._toBitPattern() print(String(format: "%#08x", bytes1)) // 0x3fc00000 let bytes2: UInt32 = 0b00111111110000000000000000000000 print(String(format: "%#08x", bytes2)) // 0x3fc00000 print(bytes1 == bytes2) // true此方法是FloatingPointType协议的一部分 Float,Double和CGFloat符合的条件:
This method is part of the FloatingPointType protocol to which Float, Double and CGFloat conform:
/// A set of common requirements for Swift's floating point types. protocol FloatingPointType : Strideable { typealias _BitsType static func _fromBitPattern(bits: _BitsType) -> Self func _toBitPattern() -> _BitsType // ... }(从Swift 2开始,这些定义在 API文档,但它们仍然存在并且可以像以前一样工作.)
(As of Swift 2, these definition are not visible anymore in the API documentation, but they still exist and work as before.)
_BitsType的实际定义在API中不可见 文档,但对于Float是UInt32,对于UInt64是UInt64 Double和Int表示CGFloat:
The actual definition of _BitsType is not visible in the API documentation, but it is UInt32 for Float, UInt64 for Double, and Int for CGFloat:
print(Float(1.0)._toBitPattern().dynamicType) // Swift.UInt32 print(Double(1.0)._toBitPattern().dynamicType) // Swift.UInt64 print(CGFloat(1.0)._toBitPattern().dynamicType) // Swift.UInt_fromBitPattern()可用于转换为其他 方向:
_fromBitPattern() can be used for the conversion into the other direction:
let y = Float._fromBitPattern(0x3fc00000) print(y) // 1.5更多推荐
在Swift中获取浮点数的原始字节
发布评论