Welcome to this comprehensive guide on Swift Bitwise Operators! This tutorial is designed to be beginner-friendly, yet comprehensive enough for intermediate learners. Let's dive into the world of binary operations, which can be quite fascinating and practical for real-world programming projects.
Bitwise operators manipulate individual bits (binary digits) within an integer. They are fundamental for low-level programming tasks such as data packing, masking, and performing logical operations on binary representations.
Before we dive into bitwise operators, let's understand binary numbers. A binary number is a number represented in the base-2 numeral system, which consists of only 0s and 1s. Each digit in a binary number is called a "bit".
Swift provides several bitwise operators, some of which are:
&: AND|: OR^: XOR (exclusive OR)~: NOT (bitwise negation)<<: Left Shift>>: Right Shift>>>>: Zero Fill Right ShiftLet's explore some practical examples to understand these operators better.
&) 💡The AND operator (&) returns 1 (true) only when both bits are 1 and 0 otherwise.
let a = 60 // binary: 00111100
let b = 13 // binary: 00001101
let result = a & b // binary: 00001000
print(result) // prints: 8|) 💡The OR operator (|) returns 1 (true) when at least one of the bits is 1.
let a = 60 // binary: 00111100
let b = 13 // binary: 00001101
let result = a | b // binary: 00111101
print(result) // prints: 61^) 💡The XOR operator (^) returns 1 (true) when the number of set bits (1s) is odd.
let a = 60 // binary: 00111100
let b = 13 // binary: 00001101
let result = a ^ b // binary: 00110101
print(result) // prints: 57~) 💡The NOT operator (~) flips all the bits of a number.
let a = 60 // binary: 00111100
let result = ~a // binary: 11000011
print(result) // prints: -62Shift operators move bits to the left or right.
let a = 60 // binary: 00111100
let b = a << 2 // binary: 11110000
print(b) // prints: 288
let c = 60 >> 2 // binary: 00001110
print(c) // prints: 10What is the result of `60 & 13`?
Stay tuned for our next tutorial, where we will dive deeper into using bitwise operators for practical tasks in Swift. Until then, happy coding! 💻🎓