在Swift中获取浮点数的原始字节 [英] Get raw bytes of a float in Swift

查看:166
本文介绍了在Swift中获取浮点数的原始字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift中读取FloatDouble的原始字节?

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

我希望bytes1bytes2包含相同的值,因为此二进制数是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.

示例: FloatUInt32:

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

示例: UInt32Float:

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

您可以用相同的方式在DoubleUInt64之间进行转换, 或在CGFloatUInt之间.

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协议的一部分 FloatDoubleCGFloat符合的条件:

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中不可见 文档,但对于FloatUInt32,对于UInt64UInt64 DoubleInt表示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中获取浮点数的原始字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆