Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

UInt8 is a value type in Swift representing an 8-bit unsigned integer. It occupies exactly one byte of memory and stores non-negative whole numbers. As a fixed-width integer, its memory footprint is deterministic regardless of the underlying hardware architecture.

Technical Specifications

  • Memory Size: 8 bits (1 byte)
  • Minimum Value (UInt8.min): 0
  • Maximum Value (UInt8.max): 255 (2812^8 - 1)
  • Protocol Conformances: UnsignedInteger, FixedWidthInteger, BinaryInteger, Hashable, Codable, Sendable.

Initialization and Literals

UInt8 can be initialized using standard decimal integers, as well as hexadecimal, octal, and binary literals.
let decimal: UInt8 = 255
let hex: UInt8     = 0xFF
let octal: UInt8   = 0o377
let binary: UInt8  = 0b1111_1111

Type Conversion

Swift does not implicitly convert between integer types. Converting another integer type to UInt8 requires explicit initialization. Because UInt8 has a narrow bounds range, Swift provides different initializers to handle potential out-of-bounds conversions:
let sourceInt: Int = 300

// 1. Standard Initializer (Traps on overflow)
// let standard = UInt8(sourceInt) // Fatal error: Not enough bits to represent the passed value

// 2. Exact Initializer (Returns nil on overflow)
let exact = UInt8(exactly: sourceInt) // nil

// 3. Truncating Initializer (Performs bitwise truncation)
let truncated = UInt8(truncatingIfNeeded: sourceInt) // 44 (300 % 256)

Arithmetic and Overflow Behavior

By default, standard arithmetic operators (+, -, *) in Swift trap (crash) if the operation results in a value outside the 0...255 range. To perform modulo arithmetic that wraps around the bounds, UInt8 utilizes Swift’s overflow operators (&+, &-, &*).
let maxVal: UInt8 = 255
let minVal: UInt8 = 0

// Overflow Addition
let wrappedAdd = maxVal &+ 1 // 0

// Overflow Subtraction
let wrappedSub = minVal &- 1 // 255

// Overflow Multiplication
let wrappedMult = maxVal &* 2 // 254

Bitwise Operations

Because UInt8 conforms to FixedWidthInteger, it fully supports bitwise manipulation. Operations are applied directly to the 8-bit underlying binary representation.
let bits: UInt8 = 0b0000_1111 // 15

// Bitwise NOT
let inverted = ~bits          // 0b1111_0000 (240)

// Bitwise AND
let masked = bits & 0b0000_1010 // 0b0000_1010 (10)

// Bitwise Left Shift
let shifted = bits << 2       // 0b0011_1100 (60)

Memory Representation

You can access the raw byte representation of a UInt8 or convert raw bytes into a UInt8 using its bitPattern initializers, which is particularly relevant when interfacing with C APIs or unsafe memory pointers.
let int8Value: Int8 = -1
let bitPattern = UInt8(bitPattern: int8Value) // 255 (0xFF)
Master Swift with Deep Grasping Methodology!Learn More