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

问题描述 投票:1回答:1

我正在尝试使用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
rust formatting number-formatting
1个回答
1
投票
println!("Base: {:>#10x}, length: {}", 0x40, 900);

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

std::fmt作为参数传递,那将是:

width
© www.soinside.com 2019 - 2024. All rights reserved.