I'm importing some old C code into a swift project, and porting it across to pure swift code.
Some of it does "encryption" wherein it does something like
let a = UInt8(x) // e.g. 30
let b = a - 237
In C this just underflows and wraps around, which is fine for this particular function.
In swift this triggers a fatalError and terminates my program with EXC_BAD_INSTRUCTION because swift by default is designed to catch integer over/underflow.
I'm aware I can turn this checking off at the entire project level by compiling with -Ofast, but I'd really like to just turn off the overflow checking for this one line of code (or perhaps just the specific function itself).
Note: I specifically want to preserve the behaviour of the C function, not just promote things up to Int32 or Int64
This particular term seems really hard to google for.
Update: The answer is the Overflow operators, which are
&-
for subtraction&+
for addition&*
for multiplyI couldn't find them in my previous searching. Oops
You can use addWithOverflow or subtractWithOverflow class method of Int, UInt8 etc types
E.g. let b = UInt8.subtractWithOverflow(a, 237)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With