本文介绍了诠释为uint(反之亦然)位在铸造斯威夫特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要寻找一个直接的方式来位投了Int的位值UINT,反之亦然。例如(使用简单的8位整数)我要实现以下目标:
I am looking for a direct way to bit cast the bit values of an Int to UInt and vice versa. For example (using the 8 bits integers for simplicity) I want to achieve the following:
let unsigned: UInt8 = toUInt8(-1) // unsigned is 255 or 0xff
let signed: Int8 = toInt8(0xff) // signed is -1
起初我想出了以下解决方案:
At first I came out with the following solution:
let unsigned = unsafeBitCast(Int8(-1), UInt8.self)
let signed = unsafeBitCast(UInt8(0xff), Int8.self)
但是,苹果在unsafeBitCast()文件规定如下:
But Apple in the "unsafeBitCast()" documentation states the following:
..注意::打破斯威夫特的类型系统的保障;与使用
格外小心。有几乎总是一个更好的方式做任何事情。
有没有人有更好的办法?
Does anyone have the better way?
推荐答案
您可以这样做:
let unsigned = UInt8(bitPattern: Int8(-1)) // -> 255
let signed = Int8(bitPattern: UInt8(0xff)) // -> -1
许多类似的初始化存在:
Many similar initializers exist:
extension Int8 {
init(_ v: UInt8)
init(_ v: UInt16)
init(truncatingBitPattern: UInt16)
init(_ v: Int16)
init(truncatingBitPattern: Int16)
init(_ v: UInt32)
init(truncatingBitPattern: UInt32)
init(_ v: Int32)
init(truncatingBitPattern: Int32)
init(_ v: UInt64)
init(truncatingBitPattern: UInt64)
init(_ v: Int64)
init(truncatingBitPattern: Int64)
init(_ v: UInt)
init(truncatingBitPattern: UInt)
init(_ v: Int)
init(truncatingBitPattern: Int)
init(bitPattern: UInt8)
}
这篇关于诠释为uint(反之亦然)位在铸造斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!