填充字符串的最简单方法是将左侧的0填充为0
我曾尝试使用format!
宏,但它只用空格填充到右边:
format!("{:08}", string);
fmt
module documentation描述了所有格式选项:
Fill / Alignment
填充字符通常与
width
参数一起提供。这表示如果格式化的值小于width
,则会在其周围打印一些额外的字符。额外的字符由fill
指定,对齐可以是以下选项之一:
<
- 参数在width
列中左对齐^
- 参数在width
专栏中居中对齐>
- 这个论点在width
专栏中是正确的
assert_eq!("00000110", format!("{:0>8}", "110"));
// |||
// ||+-- width
// |+--- align
// +---- fill
也可以看看:
作为Shepmaster答案的替代方案,如果你实际上是以数字而不是字符串开头,并且想要将其显示为二进制,那么格式化的方法是:
let n: u32 = 0b11110000;
// 0 indicates pad with zeros
// 8 is the target width
// b indicates to format as binary
let formatted = format!("{:08b}", n);