I'm trying to print something like this with Rust:
Base: 0x40, length: 900
Base: 0x5500, length: 301
Right now I have:
println!("Base: {:>width$x}, length: {}", 67106, 54, width=10);
Base: 10622, length: 54
Is there a way to get Rust to include the "0x" prefix? These two don't compile:
println!("Base: {:>width#$x}, length: {}", 67106, 54, width=10);
println!("Base: {:>width$#x}, length: {}", 67106, 54, width=10);
error: invalid format string: expected `'}'`, found `'#'`
--> src/main.rs:2:29
|
2 | println!("Base: {:>width#$x}, length: {}", 67106, 54, width=10);
| - ^ expected `}` in format string
| |
| because of this opening brace
|
= note: if you intended to print `{`, you can escape it using `{{`
error: invalid format string: expected `'}'`, found `'#'`
--> src/main.rs:3:30
|
3 | println!("Base: {:>width$#x}, length: {}", 67106, 54, width=10);
| - ^ expected `}` in format string
| |
| because of this opening brace
|
= note: if you intended to print `{`, you can escape it using `{{`
The best I have is:
println!("Base: 0x{:0>8x}, length: {}", 67106, 54);
Base: 0x00010622, length: 54
Which is probably fine, but I'm curious if there is a way to do this. Also, I thought maybe this would work, but no such luck:
println!("Base: {:>10}, length: {}", format_args!("{:#x}", 67106), 54);
Base: 0x10622, length: 54
println!("Base: {:>#10x}, length: {}", 0x40, 900);
You need to put the # before the width to set the alternate form. See the std::fmt syntax for an explanation of formatting.
With width passed as an argument, that would be:
println!("Base: {:>#width$x}, length: {}", 67106, 301, width=10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With