cheeesus cheeesus - 1 year ago 105
Swift Question

Get raw bytes of a float in Swift

How can I read the raw bytes of a

in Swift?


let x = Float(1.5)
let bytes1: UInt32 = getRawBytes(x)
let bytes2: UInt32 = 0b00111111110000000000000000000000

I want
to contain the same value, since this binary number is the Float representation of

I need it to do bit-wise operations like
(these are not defined on a float).

Answer Source

The Swift floating point types have a _toBitPattern() method:

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

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

    // ...

(As of Swift 2, these definition are not visible anymore in the API documentation, but they still exist and work as before.)

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:

// Swift.UInt32

// Swift.UInt64

// Swift.UInt

_fromBitPattern() can be used for the conversion into the other direction:

let y = Float._fromBitPattern(0x3fc00000)
print(y) // 1.5

Update for Swift 3: As of Swift 3, Float has a (public) bitPattern property and a corresponding constructor for conversion to UInt32 and back:

// Float to UInt32:
let x = Float(1.5)
let bytes1 = x.bitPattern
print(String(format: "%#08x", bytes1)) // 0x3fc00000

// UInt32 to Float:
let bytes2 = UInt32(0x3fc00000)
let y = Float(bitPattern: bytes2)
print(y) // 1.5