Rust format hex with 0x, binary with 0b, and pretty Debug
Add # to a Rust format specification when you need the formatter’s alternate representation. For standard integer bases, that means prefixes such as 0x, 0b, and 0o. With Debug, {:#?} requests the pretty representation.
assert_eq!(format!("{:#b}", 42), "0b101010");
assert_eq!(format!("{:#o}", 42), "0o52");
assert_eq!(format!("{:#x}", 42), "0x2a");
assert_eq!(format!("{:#X}", 42), "0x2A");Add 0x, 0b, or 0o prefixes
Section titled “Add 0x, 0b, or 0o prefixes”For the standard integer base formatters, # adds the conventional prefix:
| Syntax | Prefix |
|---|---|
{:#b} |
0b |
{:#o} |
0o |
{:#x} |
0x |
{:#X} |
0x |
The prefix is part of the formatted width. When alternate formatting is combined with numeric zero padding, zeros are inserted after the prefix and before the digits.
Combine # with width and zero padding
Section titled “Combine # with width and zero padding”Alternate prefixes participate in the total width. For example, "{:#010x}" includes the 0x prefix inside the ten-character minimum width, and zero padding is inserted after the prefix.
That detail matters when you are formatting fixed-width numeric columns or diagnostics. Calculate the width as the width of the entire formatted representation, not just the hexadecimal digits.
Pretty Debug with {:#?}
Section titled “Pretty Debug with {:#?}”# has a different meaning with Debug. {:#?} requests the pretty Debug representation, which derived and standard Debug implementations commonly render with line breaks and indentation.
That output is for inspection, not a stable serialization format. See pretty Debug for the stability caveat and practical use.
Custom formatters
Section titled “Custom formatters”Custom implementations can inspect whether alternate formatting was requested through the Formatter. That means # is a signal to the formatting trait implementation, not a generic post-processing step.
When you are reading an unfamiliar custom formatter, check the trait implementation before assuming what # means.