Rust format hex, binary, octal, and scientific notation
Rust formats hexadecimal with {:x} or {:X}, binary with {:b}, octal with {:o}, and scientific notation with {:e} or {:E}. These suffixes select formatting traits rather than converting the value manually.
let value = 42;
assert_eq!(format!("{value:b}"), "101010");
assert_eq!(format!("{value:o}"), "52");
assert_eq!(format!("{value:x}"), "2a");
assert_eq!(format!("{value:X}"), "2A");
assert_eq!(format!("{:e}", 42.0), "4.2e1");Format numbers as hex, binary, or octal
Section titled “Format numbers as hex, binary, or octal”| Syntax | Trait | Example purpose |
|---|---|---|
{:b} |
Binary |
base 2 |
{:o} |
Octal |
base 8 |
{:x} |
LowerHex |
lower-case base 16 |
{:X} |
UpperHex |
upper-case base 16 |
{:e} |
LowerExp |
scientific notation with e |
{:E} |
UpperExp |
scientific notation with E |
The suffix selects a trait, not a conversion function. Any type that implements the corresponding trait can use that syntax, including custom types.
Uppercase and lowercase hexadecimal
Section titled “Uppercase and lowercase hexadecimal”Lower and upper hexadecimal are separate formatting traits. {:x} selects LowerHex; {:X} selects UpperHex. Scientific notation follows the same pattern with e and E.
That makes the requested representation explicit in the format string. There is no later case-conversion step hidden behind the syntax.
Add 0x, 0b, or 0o prefixes
Section titled “Add 0x, 0b, or 0o prefixes”{:x} produces hexadecimal digits but no 0x prefix. Add the alternate flag to request the prefixed form:
{:#x}The same pattern applies to binary and octal. See alternate formatting with # for the exact prefixes and its separate meaning for Debug.
Width and zero padding still apply
Section titled “Width and zero padding still apply”Type suffixes can be combined with other formatting parameters. For example, hexadecimal output can have a minimum width and sign-aware zero padding. The order is defined by the format grammar, so it is better to build the specification from its parts than memorize punctuation.
Use the format specifier grammar when combining several flags at once.