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)
But Apple in the "unsafeBitCast()" documentation states the following:
.. Caution:: Breaks the guarantees of Swift's type system; use with
extreme care. There's almost always a better way to do anything.
Does anyone have the better way?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…