Swift Bitwise Operators Tutorial 🎯

beginner
19 min

Swift Bitwise Operators Tutorial 🎯

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.

Understanding Bitwise Operators 📝

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.

Binary Numbers 💡

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

Common Bitwise Operators 📝

Swift provides several bitwise operators, some of which are:

  • &: AND
  • |: OR
  • ^: XOR (exclusive OR)
  • ~: NOT (bitwise negation)
  • <<: Left Shift
  • >>: Right Shift
  • >>>>: Zero Fill Right Shift

Practical Examples 💡

Let's explore some practical examples to understand these operators better.

AND Operator (&) 💡

The AND operator (&) returns 1 (true) only when both bits are 1 and 0 otherwise.

swift
let a = 60 // binary: 00111100 let b = 13 // binary: 00001101 let result = a & b // binary: 00001000 print(result) // prints: 8

OR Operator (|) 💡

The OR operator (|) returns 1 (true) when at least one of the bits is 1.

swift
let a = 60 // binary: 00111100 let b = 13 // binary: 00001101 let result = a | b // binary: 00111101 print(result) // prints: 61

XOR Operator (^) 💡

The XOR operator (^) returns 1 (true) when the number of set bits (1s) is odd.

swift
let a = 60 // binary: 00111100 let b = 13 // binary: 00001101 let result = a ^ b // binary: 00110101 print(result) // prints: 57

NOT Operator (~) 💡

The NOT operator (~) flips all the bits of a number.

swift
let a = 60 // binary: 00111100 let result = ~a // binary: 11000011 print(result) // prints: -62

Shift Operators 💡

Shift operators move bits to the left or right.

swift
let a = 60 // binary: 00111100 let b = a << 2 // binary: 11110000 print(b) // prints: 288 let c = 60 >> 2 // binary: 00001110 print(c) // prints: 10

Quiz 🎯

Quick Quiz
Question 1 of 1

What 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! 💻🎓