carlossless
carlossless

Reputation: 1181

Hexadecimal formatting with padded zeroes

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

Upvotes: 9

Views: 6836

Answers (1)

dtolnay
dtolnay

Reputation: 10993

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.

Upvotes: 18

Related Questions