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.

UInt16 is a value type in Swift representing an unsigned 16-bit (2-byte) fixed-width integer. Because it is unsigned, it cannot represent negative numbers, allocating all 16 bits entirely to represent positive magnitudes and zero.

Value Range and Bounds

As a 16-bit unsigned integer, UInt16 has a strictly defined mathematical range:
  • Minimum Value: 0
  • Maximum Value: 65535 (21612^{16} - 1)
You can access these bounds programmatically using static properties:
let lowestValue = UInt16.min  // 0
let highestValue = UInt16.max // 65535
let width = UInt16.bitWidth   // 16

Initialization and Literals

UInt16 can be initialized using standard base-10 integer literals, as well as hexadecimal, octal, and binary literals. Swift allows the use of underscores (_) for visual grouping.
let decimal: UInt16 = 65000
let hex: UInt16 = 0xFEF8
let octal: UInt16 = 0o176570
let binary: UInt16 = 0b1111_1101_1110_1000

Type Conversion

Swift does not implicitly convert between integer types. To assign a value from another integer type (like Int, UInt8, or UInt32) to a UInt16, you must perform an explicit initialization. If the source value exceeds the bounds of UInt16, a runtime trap occurs.
let eightBit: UInt8 = 250
let sixteenBit = UInt16(eightBit) // Explicit promotion to UInt16

let largeInt: Int = 70000
// let invalid = UInt16(largeInt) // Fatal error: Not enough bits to represent the passed value

let exactConversion = UInt16(exactly: largeInt) // Returns nil instead of crashing

Overflow and Underflow Behavior

By default, Swift arithmetic operators (+, -, *) trap and crash the application if an operation exceeds the bounds of UInt16. To perform modulo arithmetic that wraps around the type’s boundaries, you must use Swift’s overflow operators (&+, &-, &*).
var maxVal = UInt16.max // 65535

// Standard addition traps on overflow
// maxVal += 1 // Fatal error: arithmetic overflow

// Overflow addition wraps to the minimum value
let wrappedAdd = maxVal &+ 1 // 0

var minVal = UInt16.min // 0

// Overflow subtraction wraps to the maximum value
let wrappedSub = minVal &- 1 // 65535

Endianness and Memory Layout

Because UInt16 occupies multiple bytes in memory, its byte order (endianness) is relevant. UInt16 provides properties to inspect and manipulate its byte representation relative to the host architecture.
let value: UInt16 = 0x1234

// Swaps the high-order and low-order bytes
let swapped = value.byteSwapped // 0x3412

// Accessing specific endian representations
let bigEndianValue = value.bigEndian
let littleEndianValue = value.littleEndian
Master Swift with Deep Grasping Methodology!Learn More