Converting signed to unsigned in Swift

前端 未结 2 566
失恋的感觉
失恋的感觉 2020-12-06 11:08

In C, I am able to do a trick with numbers:

uint8_t value = 0
int delta = -1
uint8_t result = value + delta  /* result will be 0xFF */

Is

相关标签:
2条回答
  • 2020-12-06 11:47

    All signed and unsigned integer types have a bitPattern: constructor, which creates an unsigned number from a signed (or vice versa) with the same memory representation:

    let delta: Int8 = -1
    let result: UInt8 = UInt8(bitPattern: delta) // 0xFF = 255
    
    0 讨论(0)
  • 2020-12-06 12:10

    (I think your example is a little off. 0 - -1 is 1. I believe this answer is what you were thinking of, though).

    You want to opt-into overflow with the &- operator:

    let value: UInt8 = 0
    let delta: UInt8 = 1
    let result: UInt8 = value &- delta
    

    There are similar things you can do with the other & operators like &+, &*, etc. There's even a &/ that handles divide by zero.

    0 讨论(0)
提交回复
热议问题