在 Swift 中将有符号转换为无符号 [英] Converting signed to unsigned in Swift

查看:41
本文介绍了在 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... 

有没有办法在 Swift 中获得 C 的减法行为?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆