在Swift中将有符号转换为无符号 [英] Converting signed to unsigned in Swift
本文介绍了在Swift中将有符号转换为无符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C语言中,我可以用数字做些技巧:
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 */
在Swift中有没有办法做到这一点?请注意,相同的方法无效:
Is there a way of doing the same in Swift? Notice that the same approach doesn't work:
let value: UInt8 = 0
let delta: Int = -1
var result: UInt8 = value + delta // Error, even typecasting in different ways...
是否有一种方法可以让C的行为在Swift中进行减法运算?
Is there a way to get C's behaviour for substraction in Swift?
谢谢!
推荐答案
所有有符号和无符号整数类型都有一个bitPattern:
构造函数,
它从具有相同符号的已签名(反之亦然)中创建一个未签名的数字
内存表示形式:
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
这篇关于在Swift中将有符号转换为无符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文