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

前端 未结 3 663
隐瞒了意图╮
隐瞒了意图╮ 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:12

    You can do:

    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)
    }
    

提交回复
热议问题