Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to right justify a hexadecimal number with "0x" in Rust?

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
like image 561
Brad Avatar asked Nov 19 '25 11:11

Brad


1 Answers

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);
like image 94
KamilCuk Avatar answered Nov 22 '25 03:11

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!