Sub topic 11
Hex, Binary, Octal, and Exponent Output
This chapter covers the format type characters that print integers in other bases and floats in scientific notation. It assumes you know the basic {} placeholder, width, fill, and alignment, and the 0 flag from the earlier chapters. You should also know what a trait is, because each type character maps to a trait.
The type characters
The part after the colon in a placeholder can end with a type character. With no character, Rust uses Display. With ?, it uses Debug. The characters below select other traits from std::fmt.
| Spec | Trait | Meaning | Works on |
|---|---|---|---|
| `x` | `LowerHex` | hexadecimal, lowercase digits | integers |
| `X` | `UpperHex` | hexadecimal, uppercase digits | integers |
| `o` | `Octal` | base 8 | integers |
| `b` | `Binary` | base 2 | integers |
| `e` | `LowerExp` | scientific notation, lowercase `e` | floats and integers |
| `E` | `UpperExp` | scientific notation, uppercase `E` | floats and integers |
If a type does not implement the selected trait, the program fails to compile. Writing {:x} for an f64 or a String is an error, not a run-time surprise.
Hex, octal, and binary
fn main() {
let n = 255;
println!("{:x}", n);
println!("{:X}", n);
println!("{:o}", n);
println!("{:b}", n);
}This prints ff, FF, 377, and 11111111, one per line. None of these outputs carries a prefix or leading zeros unless you ask for them.
The `#` flag adds a prefix
The alternate flag # places a base prefix before the digits.
fn main() {
let n = 255;
println!("{:#x}", n);
println!("{:#X}", n);
println!("{:#o}", n);
println!("{:#b}", n);
}The output is 0xff, 0xFF, 0o377, and 0b11111111. The prefix is always lowercase, even with X. Only the digits change case.
Padding and width
Width, fill, alignment, and the 0 flag work as they do for decimal numbers. The common idiom for a fixed-width binary or hex value is 0 plus a width.
fn main() {
println!("{:08b}", 37);
println!("{:02x}", 10);
println!("[{:>8x}]", 255);
println!("{:#010b}", 5);
println!("{:#06x}", 255);
}This prints 00100101, 0a, [ ff], 0b00000101, and 0x00ff.
The width includes the prefix. {:#010b} gives ten characters in total: 0b followed by eight digits. A common mistake is to write {:#08x} and expect eight digits after 0x. You get six.
Negative integers
Radix formatting shows the two's complement bit pattern at the width of the type. The type decides how many digits appear.
fn main() {
let a: i8 = -1;
let b: i32 = -1;
let c: i8 = -5;
println!("{:x}", a);
println!("{:x}", b);
println!("{:b}", c);
}The output is ff, ffffffff, and 11111011. Rust does not print -1 in hex as -1, and it does not print a minus sign in any radix. If you want a signed hex display, format the absolute value yourself and add the sign.
An untyped integer literal defaults to i32. So {:x} of -1 with no annotation gives eight f digits.
Hex dumps of bytes
Two-digit lowercase hex per byte is the usual way to print hashes, keys, and buffers. The 02 makes small values keep their leading zero.
fn main() {
let bytes = [0xde_u8, 0xad, 0xbe, 0xef, 0x01];
let hex: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
println!("{hex}");
let (r, g, b) = (255, 128, 0);
println!("#{:02x}{:02x}{:02x}", r, g, b);
}This prints deadbeef01 and then #ff8000. The iterator yields &u8. References forward formatting to the value they point to, so {:02x} works on them directly.
Hex inside Debug output
{:?} prints integers in a collection in decimal. Adding x or X before the ? switches the integers inside to hex while keeping the Debug layout.
fn main() {
let v = vec![10, 255, 4096];
println!("{:?}", v);
println!("{:x?}", v);
println!("{:X?}", v);
println!("{:02x?}", vec![1, 10, 255]);
}The output is [10, 255, 4096], [a, ff, 1000], [A, FF, 1000], and [01, 0a, ff]. The flags apply to every integer inside the value. This works with derived Debug too, so a struct of numeric fields can be printed in hex without extra code.
Exponent notation
{:e} and {:E} print a number as a mantissa and a power of ten. The mantissa has one digit before the point.
fn main() {
println!("{:e}", 1234.5);
println!("{:E}", 1234.5);
println!("{:e}", 0.00012);
println!("{:e}", 1500);
println!("{:.2e}", 1234.5);
}This prints:
1.2345e31.2345E31.2e-41.5e31.23e3
Rust prints the exponent without a plus sign or zero padding, so you get e3, not e+03 as in C. The default output uses as many digits as are needed to read the value back exactly. A precision such as .2 fixes the number of digits after the point in the mantissa.
Plain {} on a float never switches to exponent form. A very large f64 prints all of its digits. If you want compact output for huge or tiny values, ask for {:e}.
Implementing the radix traits
The radix and exponent traits have the same shape as Display. A newtype often forwards to the inner value so that all flags keep working.
use std::fmt;
struct Id(u32);
impl fmt::LowerHex for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(&self.0, f)
}
}
fn main() {
let id = Id(48879);
println!("{:x}", id);
println!("{:#010x}", id);
}This prints beef and then 0x0000beef. Passing the same Formatter to the inner type's fmt keeps the width, fill, #, and 0 flags. If you used write!(f, "{:x}", self.0) instead, the caller's flags would be lost.
Common mistakes
- Using
{:x}on a float, string, orchar. These types do not implement the trait, so compilation fails. - Expecting
{:#08x}to give eight digits. The0xtakes two of the eight characters. - Expecting a minus sign for negative values in hex or binary. You get the bit pattern at the type's width.
- Expecting
{:#X}to print0XFF. The prefix stays0x. - Reading
{:e}output as C-style. There is no+and no padded exponent.
Exercise
What does println!("{:#010b}", 5) print, and why is the result ten characters long?
Show answer
It prints 0b00000101. The width of 10 includes the two-character 0b prefix, and the 0 flag pads the eight remaining positions with zeros.
Exercise
What do println!("{:x}", -1i16) and println!("{:x?}", vec![255, 16]) print?
Show answer
The first prints ffff, the two's complement pattern of an i16, which has four hex digits. The second prints [ff, 10], because x? formats each integer inside the Debug output in hex.
Exercise
Write a format string that prints the byte value 7u8 as 07 in hex, and the float 0.00012 as 1.20e-4.
Show answer
Use {:02x} for the byte, which gives 07. Use {:.2e} for the float, which gives 1.20e-4.