Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexadecimal formatting with padded zeroes

Tags:

rust

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
like image 325
carlossless Avatar asked Dec 14 '22 18:12

carlossless


1 Answers

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.

like image 80
dtolnay Avatar answered Dec 19 '22 11:12

dtolnay