Ori*_*rds 6 integer-overflow swift
我正在将一些旧的C代码导入到一个快速项目中,并将其移植到纯粹的快速代码中.
其中一些做"加密",其中它做了类似的事情
let a = UInt8(x) // e.g. 30
let b = a - 237
Run Code Online (Sandbox Code Playgroud)
在C中,这只是下溢和环绕,这对于这个特定的功能来说很好.
在swift中,这会触发fatalError并使用EXC_BAD_INSTRUCTION终止我的程序,因为默认情况下swift用于捕获整数上溢/下溢.
我知道我可以通过使用-Ofast进行编译来在整个项目级别关闭此检查,但我真的想关闭这一行代码的溢出检查(或者可能只是特定的函数本身).
注意:我特别想保留C函数的行为,而不仅仅是将事物提升到Int32或Int64
这个特殊的术语似乎很难谷歌.
更新:答案是溢出运算符,它们是
&- 减法&+ 另外&* 为了倍增我在之前的搜索中找不到它们.哎呀
除了溢出运算符(例如 &+ 、 &* 等)之外,您还可以利用报告溢出方法(适用于整数)来了解算术运算是否导致溢出,如下例所示:
let int1 : Int8 = Int8.max //127
let int2: Int8 = 50
//this method provides a boolean flag
let (sum1,didOverflow ):(Int8,Bool) = int1.addingReportingOverflow(int2)
print("sum is \(sum1) and isOverflowing = \(didOverflow)")
//sum is -79 and isOverflowing is true
let sum = int1 &+ int2 //wont crash for overflows
let unsafeSum = int1.unsafeAdding(int2) //crashes whenever overflow
Run Code Online (Sandbox Code Playgroud)
您可以使用Int,UInt8等类型的addWithOverflow或subtractWithOverflow类方法
例如 let b = UInt8.subtractWithOverflow(a, 237)
| 归档时间: |
|
| 查看次数: |
1686 次 |
| 最近记录: |