Converting signed to unsigned in Swift

房东的猫 提交于 2019-11-27 23:51:20

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

(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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!