8

When formatting integer types to hexadecimal strings, I cannot get it to pad the numbers with zeroes:

println!("{:#4x}", 0x0001 as u16) // => "0x1", but expected "0x0001"
println!("{:#02x}", 0x0001 as u16) // => "0x1", same
Cœur
  • 37,241
  • 25
  • 195
  • 267
carlossless
  • 1,171
  • 8
  • 23
  • 2
    Your second question is a duplicate of [this one](https://stackoverflow.com/q/44711012/1233251) – E_net4 Feb 25 '18 at 11:27
  • 1
    Actually, the first `println!` prints ` 0x1` (with a leading space) and the second one prints `0x01`. You just have to consider that the `0x` is counted in the requested length. `println!("{:#06x}", 0x0001 as u16);` will print `0x0001`. – Francis Gagné Feb 25 '18 at 14:06

1 Answers1

17

Keep in mind that the leading 0x is counted in the length so if you want something printed as 0x0001 then the length is really going to be 6, not 4.

fn main() {
    println!("{:#06x}", 0x0001u16);
}

This prints 0x0001 as you wanted.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
dtolnay
  • 9,621
  • 5
  • 41
  • 62