13

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 */

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

Is there a way to get C's behaviour for substraction in Swift?

Thanks!

George
  • 1,235
  • 10
  • 23

2 Answers2

26

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
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Only one correction is needed, I see: 'UInt8(bitPattern: Int8(delta))' is needed instead of simple 'UInt8(bitPattern: delta)' (or delta needs to be Int8). – George Sep 04 '14 at 13:48
6

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

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Oh! Sorry... The code was wrong (typing too fast...). It is corrected now. – George Sep 04 '14 at 13:42
  • 2
    With the corrected sample code, the other answer works better, but this is useful information anyway. Thanks! – George Sep 04 '14 at 13:49