用 0 向左填充字符串的最简单方法是什么?

What is the easiest way to pad a string with 0 to the left?

用 0 向左填充字符串的最简单方法是什么

我曾尝试使用 format! 宏,但它只能向右填充 space:

format!("{:08}", string);

fmt module documentation描述了所有格式选项:

Fill / Alignment

The fill character is provided normally in conjunction with the width parameter. This indicates that if the value being formatted is smaller than width some extra characters will be printed around it. The extra characters are specified by fill, and the alignment can be one of the following options:

  • < - the argument is left-aligned in width columns
  • ^ - the argument is center-aligned in width columns
  • > - the argument is right-aligned in width columns

assert_eq!("00000110", format!("{:0>8}", "110"));
//                                |||
//                                ||+-- width
//                                |+--- align
//                                +---- fill

另请参阅:

  • Convert binary string to hex string with leading zeroes in Rust

作为 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);