Use Bitwise Operators in Swift
Written by Team Kodeco
Swift provides a set of bitwise operators that allow you to manipulate the individual bits in an integer value. These operators are particularly useful for working with low-level data structures or for implementing certain types of algorithms.
The Bitwise NOT Operator (~)
The bitwise NOT operator (~) inverts the bits of an integer value. This operator is equivalent to the logical NOT operator (!) for Boolean values. The following code snippet shows an example of how to use the bitwise NOT operator:
let x: UInt8 = 0b00001111 // Binary 00001111, Decimal 15
let y = ~x // Binary 11110000, Decimal 240
The Bitwise AND Operator (&)
The bitwise AND operator (&) compares each bit of two integer values and returns a new value that has a 1 in each bit position where both input values have a 1. The following code snippet shows an example of how to use the bitwise AND operator:
let x: UInt8 = 0b01010101 // Binary 01010101, Decimal 85
let y: UInt8 = 0b00110011 // Binary 00110011, Decimal 51
let z = x & y // Binary 00010001, Decimal 17
The Bitwise OR Operator (|)
The bitwise OR operator (|) compares each bit of two integer values and returns a new value that has a 1 in each bit position where at least one of the input values has a 1. The following code snippet shows an example of how to use the bitwise OR operator:
let x: UInt8 = 0b01010101 // Binary 01010101, Decimal 85
let y: UInt8 = 0b00110011 // Binary 00110011, Decimal 51
let z = x | y // Binary 01110111, Decimal 119
The Bitwise XOR Operator (^)
The bitwise XOR operator (^) compares each bit of two integer values and returns a new value that has a 1 in each bit position where the input values are different. The following code snippet shows an example of how to use the bitwise OR operator:
let x: UInt8 = 0b01010101 // Binary 01010101, Decimal 85
let y: UInt8 = 0b00110011 // Binary 00110011, Decimal 51
let z = x ^ y // Binary 01100110, Decimal 102