DevPrep

All topics › Programming basics

Bit and byte

Junior

Essence

A bit is the smallest unit of information: 0 or 1. A byte is the smallest addressable unit of memory; on every modern platform, Apple's included, it is 8 bits, i.e. 256 (2⁸) possible values. Everything a program stores or sends — numbers, strings, images, pointers — is a sequence of bytes, and the type tells the compiler how to interpret those bytes.

In Swift

let a: UInt8 = 0b1010_0101           // 165
print(UInt8.max)                     // 255
print(MemoryLayout<Int>.size)        // 8 on a 64-bit platform
print(MemoryLayout<Bool>.size)  // 1 — even a single flag takes a whole byte

let flags: UInt8 = 0b0000_0101
print(flags & 0b100 != 0)            // true — the third bit is set
print(flags << 1)                    // 10 — left shift = multiply by 2
print(Int8(bitPattern: 0xFF))  // -1 — same 8 bits, different interpretation

What the interviewer looks for

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store