How to format a byte into a 2 digit hex string, in Rust [duplicate]

As documented in the std::fmt module:

# – This flag is indicates that the “alternate” form of printing should be used. The alternate forms are:

  • #x – precedes the argument with a 0x
  • #X – precedes the argument with a 0x

This interacts with the request width, because the width accounts for the whole substitution and thus 0x0a is 4 characters, not 2.

If you request a width that is less than the necessary width, the requested width is disregarded and the minimum width is used instead (here 3 characters).

A quick experiment on the playground:

fn main() {
    println!("{:#01x}", 10);
    println!("{:#02x}", 10);
    println!("{:#03x}", 10);
    println!("{:#04x}", 10);
    println!("{:#05x}", 10);
    println!("{:#06x}", 10);
}

Prints:

0xa
0xa
0xa
0x0a
0x00a
0x000a

All is well.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)