我正在寻找一种直接的方法来位转换为UInt的Int的位值,反之亦然。例如(为简单起见,使用8位整数)我希望实现以下目标:
let unsigned: UInt8 = toUInt8(-1) // unsigned is 255 or 0xff
let signed: Int8 = toInt8(0xff) // signed is -1
首先,我提出了以下解决方案:
let unsigned = unsafeBitCast(Int8(-1), UInt8.self)
let signed = unsafeBitCast(UInt8(0xff), Int8.self)
但苹果在"unsafeBitCast()“文档中声明了以下内容:
..注意::破坏了Swift类型系统的保证;使用时要格外小心。几乎总是有更好的方法来做任何事情。
有谁有更好的办法吗?
https://stackoverflow.com/questions/27127124
复制相似问题