Format Integers As Hex Binary And Octal

Render integers in binary, octal, and hex with the b, o, and x format specs, including zero padding and the # prefix variants.

RustData Integrity

Code

rustsnippet
26 lines
// 逐字节十六进制行:hex dump 的最小单元
fn hex_row(bytes: &[u8]) -> String {
    bytes
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect::<Vec<_>>()
        .join(" ")
}

fn main() {
    let flags = 0b1010u16;
    let mode = 0o750u32;
    let color = 0x1f_ff3bu32;
    let small = 0xau32;

    println!("binary: {flags:b}");
    println!("padded: {flags:08b}");
    println!("octal: {mode:o}");
    println!("hex lower: {color:x}");
    println!("hex upper: {color:X}");
    println!("prefixed: {color:#x}");
    println!("zero filled: {small:#08x}");

    let payload = [0x1f, 0xff, 0x3b, 0x0a];
    println!("hex row: {}", hex_row(&payload));
}

Format specs per radix

The literals 0b1010u16, 0o750u32, and 0x1f_ff3bu32 print through {flags:b}, {mode:o}, {color:x} (lowercase hex) and {color:X} (uppercase), so one integer type covers binary, octal, and hex without manual conversion.

Padding and prefixes

{flags:08b} zero-pads binary to 8 digits; {color:#x} adds the 0x prefix; {small:#08x} combines prefix, zero fill, and width — all expressed inside the format string.

Hex dump rows

hex_row maps each byte through format!(“{b:02x}”) and joins with spaces, the minimal unit of a hex dump; the demo prints payload [1f ff 3b 0a] as a two-digit-per-byte row.

Interactive Tools for This Topic

FAQ

How do you zero-pad a hex value to 8 digits with a prefix?
Use the combined spec {:#08x} — the demo prints small that way, producing a prefixed, zero-filled, width-8 rendering.
What does the # flag add?
The radix prefix: 0b for binary, 0o for octal, 0x/0X for hex, as shown by the prefixed line.