Int to UInt (and vice versa) bit casting in Swift

前端 未结 3 679
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 01:39

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 follo

3条回答
  •  孤街浪徒
    2020-12-14 02:25

    I took the algebra route. Testing has been a pain because it is easy to get an overflow with the strong typing breaking the execution, PlayGround returned a negative value from the toUInt function, it kept crashing or gave funny errors doing a double casting (I opened a bug report). Anyway this is what I ended up with:

    func toUint(signed: Int) -> UInt {
    
        let unsigned = signed >= 0 ?
            UInt(signed) :
            UInt(signed  - Int.min) + UInt(Int.max) + 1
    
        return unsigned
    }
    
    func toInt(unsigned: UInt) -> Int {
    
        let signed = (unsigned <= UInt(Int.max)) ?
            Int(unsigned) :
            Int(unsigned - UInt(Int.max) - 1) + Int.min
    
        return signed
    }
    

    I tested them with all extreme values (UInt.min, UInt.max, Int.min, Int.max) and when XCode doesn't go crazy it seems to work, but it looks overly complicated. Bizarre enough the UInt to Int bit casting could be simply achieved with the hashvalue property as in:

    signed = UInt.max.hashValue // signed is -1
    

    But obviously it isn't guaranteed to always work (it should, but I'd rather not taking the chance).

    Any other idea will be appreciated.

提交回复
热议问题