有没有一种方法可以在Rust中用“ 0x”对一个十六进制数进行右对齐?

时间:2019-10-25 20:18:02

标签: rust formatting number-formatting

我正在尝试用Rust打印这样的东西:

Base:       0x40, length: 900
Base:     0x5500, length: 301

现在我有:

println!("Base: {:>width$x}, length: {}", 67106, 54, width=10);
Base:      10622, length: 54

是否有办法让Rust包含“ 0x”前缀?这两个不能编译:

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 `{{`

我最好的是:

println!("Base: 0x{:0>8x}, length: {}", 67106, 54);
Base: 0x00010622, length: 54

这也许还可以,但是我很好奇是否有办法做到这一点。另外,我认为这也许行得通,但是没有运气:

println!("Base: {:>10}, length: {}", format_args!("{:#x}", 67106), 54);
Base: 0x10622, length: 54

1 个答案:

答案 0 :(得分:1)

println!("Base: {:>#10x}, length: {}", 0x40, 900);

您需要将#放在宽度之前,以设置其他格式。有关格式的说明,请参见std::fmt syntax

width作为参数传递,将是:

println!("Base: {:>#width$x}, length: {}", 67106, 301, width=10);