通常需要将一个字节打印为 2 个十六进制数字,例如 10
应该给出 0x0a
。在 Rust 中,人们会使用类似 println!("{:#02x}", 10)
的东西,但它会给出 0xa
。
我尝试过的事情列表(使用来自 std::fmt
和 fmt::LowerHex
的信息以及几个 StackOverflow 问题):
println!("{:#02x}", 10);
println!("{:#0x}", 10);
println!("{:#x}", 10);
println!("{:#x?}", 10);
println!("{:#0x?}", 10);
println!("{:#02x?}", 10);
它们都输出 0xa
,而不是 0x0A
的预期行为。
此问题已被编辑(删除相关情绪),随后被标记为与其他问题重复。但是其他答案没有解决为什么上面的列表不起作用。 #
格式选项会导致意外输出 (0xa
),尤其是 02
,一点效果都没有! 没有其他问题关注此问题,也没有特别关注 #
。
如 std::fmt
中所述模块:
#
- This flag is indicates that the "alternate" form of printing should be used. The alternate forms are:
#x
- precedes the argument with a 0x
#X
- precedes the argument with a 0x
这与请求宽度相互作用,因为宽度占整个替换,因此 0x0a
是 4 个字符,而不是 2 个。
如果您请求的宽度小于必要的宽度,则请求的宽度将被忽略,而是使用最小宽度(此处为 3 个字符)。
快速实验 on the playground :
fn main() {
println!("{:#01x}", 10);
println!("{:#02x}", 10);
println!("{:#03x}", 10);
println!("{:#04x}", 10);
println!("{:#05x}", 10);
println!("{:#06x}", 10);
}
打印:
0xa
0xa
0xa
0x0a
0x00a
0x000a
一切顺利