Understanding Swift - Bitwise Operators
Introduction
Bitwise operators in Swift are used to perform operations at the bit
level. These operators are commonly used in low-level programming,
bitwise calculations, and communication networks to manipulate
binary data efficiently. Bitwise operations do not cause overflow,
as the results always stay within the range of the given numeric
type.
Swift supports the following bitwise operators:
- Bitwise NOT (~)
- Bitwise AND (&)
- Bitwise OR (|)
- Bitwise XOR (^)
- Bitwise Left Shift (<<)
- Bitwise Right Shift (>>)
Bitwise NOT Operator (~)
The bitwise NOT operator (~) inverts all bits of the operand, changing 0s to 1s and 1s to 0s. This is also known as the one's complement of a number.
Syntax
~variableName
Example
import
Foundation
var num:
UInt8 =
0b00011111
var result
= ~num
print("Original bits:", String(num,
radix: 2))
print("One's complement:", String(result, radix: 2))
Output
One's complement: 11100000
Bitwise AND Operator (&)
The bitwise AND operator (&) performs a bitwise AND operation between two operands. It returns 1 if both corresponding bits are 1; otherwise, it returns 0.
operand1 & operand2
Example
import
Foundation
var num1:
UInt8 =
0b1000101
var num2:
UInt8 =
0b1100011
var result
= num1
& num2
print("Result:",
String(result,
radix: 2))
Output
Bitwise OR Operator (|)
The bitwise OR operator (|) compares each bit of two numbers and returns 1 if at least one of the corresponding bits is 1.
Syntax
operand1 | operand2
Example
import
Foundation
var num1:
UInt8 =
0b1010001
var num2:
UInt8 =
0b1100011
var result
= num1
| num2
print("Result:",
String(result,
radix: 2))
Output
Bitwise XOR Operator (^)
The bitwise XOR operator (^) returns 1 if one of the corresponding bits is 1 and the other is 0, otherwise returns 0.
Syntax
operand1 ^ operand2
Example
import
Foundation
var num1:
UInt8 =
0b1011001
var num2:
UInt8 =
0b1100011
var result
= num1
^ num2
print("Result:",
String(result,
radix: 2))
Output
Bitwise Right Shift Operator (>>)
The bitwise right shift operator (>>) moves the bits of a number to the right by a specified number of positions. The vacated positions are filled with zeros for unsigned integers.
Syntax
operand1 >> operand2
Examples
import
Foundation
let number:
UInt8 =
32
let shiftedNum
= number
>> 2
print("Original Number:", number)
print("Shifted Number:", shiftedNum)
Output
Shifted Number: 8