Skip to main content
u16 is a primitive unsigned 16-bit integer type in Rust. It occupies exactly 2 bytes of memory and represents non-negative whole numbers ranging from 0 to 65,535 (21612^{16} - 1). Because it is unsigned, it cannot represent negative values and uses all 16 bits to store the magnitude of the number.

Memory Layout and Bounds

The bounds of a u16 are defined by associated constants in the standard library:
  • u16::MIN: 0
  • u16::MAX: 65535

Syntax and Initialization

You can declare a u16 using explicit type annotation, literal suffixes, or rely on the compiler’s type inference. Rust also supports visual separators (_) and various radix representations (hexadecimal, octal, binary).

Type Casting and Truncation

Conversions between u16 and other primitive numeric types are performed using the as keyword. When casting to a smaller type (e.g., u8), Rust truncates the higher-order bits. When casting to a larger type (e.g., u32), Rust performs zero-extension, filling the new higher-order bits with zeros.

Overflow Behavior

Like all Rust integers, u16 has strict overflow behavior determined by the compilation profile:
  • Debug mode (dev): Integer operations that exceed u16::MAX or drop below u16::MIN will trigger a runtime panic.
  • Release mode (release): Operations silently wrap around using two’s complement wrapping (e.g., 65535 + 1 becomes 0).
To explicitly control overflow behavior regardless of the compilation profile, u16 provides dedicated method families:

Endianness and Byte Manipulation

Because u16 is a multi-byte type, its memory representation is subject to endianness (byte order). The standard library provides methods to convert a u16 to and from raw byte arrays ([u8; 2]) in specific byte orders.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More