Swift Language Bitwise Operators

Example

Swift Bitwise operators allow you to perform operations on the binary form of numbers. You can specify a binary literal by prefixing the number with 0b, so for example 0b110 is equivalent to the binary number 110 (the decimal number 6). Each 1 or 0 is a bit in the number.

Bitwise NOT ~:

var number: UInt8 = 0b01101100
let newNumber = ~number
// newNumber is equal to 0b01101100

Here, each bit get changed to its opposite. Declaring the number as explicitly UInt8 ensures that the number is positive (so that we don't have to deal with negatives in the example) and that it is only 8 bits. If 0b01101100 was a larger UInt, there would be leading 0s that would be converted to 1s and become significant upon inversion:

var number: UInt16 = 0b01101100
// number equals 0b0000000001101100
// the 0s are not significant
let newNumber = ~number
// newNumber equals 0b1111111110010011
// the 1s are now significant
  • 0 -> 1
  • 1 -> 0

Bitwise AND &:

var number = 0b0110
let newNumber = number & 0b1010
// newNumber is equal to 0b0010

Here, a given bit will be 1 if and only if the binary numbers on both sides of the & operator contained a 1 at that bit location.

  • 0 & 0 -> 0
  • 0 & 1 -> 0
  • 1 & 1 -> 1

Bitwise OR |:

var number = 0b0110
let newNumber = number | 0b1000
// newNumber is equal to 0b1110

Here, a given bit will be 1 if and only if the binary number on at least one side of the | operator contained a 1 at that bit location.

  • 0 | 0 -> 0
  • 0 | 1 -> 1
  • 1 | 1 -> 1

Bitwise XOR (Exclusive OR) ^:

var number = 0b0110
let newNumber = number ^ 0b1010
// newNumber is equal to 0b1100

Here, a given bit will be 1 if and only if the bits in that position of the two operands are different.

  • 0 ^ 0 -> 0
  • 0 ^ 1 -> 1
  • 1 ^ 1 -> 0

For all binary operations, the order of the operands makes no difference on the result.