Каков самый простой способ дополнить строку 0 слева, чтобы
"110" = "00000110"
"11110000" = "11110000"
Я пробовал использовать макрос format!, но он заполняет пробелом только вправо:
format!("{:08}", string);

Документация по модулю fmt описывает все параметры форматирования:
Fill / Alignment
The fill character is provided normally in conjunction with the
widthparameter. This indicates that if the value being formatted is smaller thanwidthsome extra characters will be printed around it. The extra characters are specified byfill, and the alignment can be one of the following options:
<- the argument is left-aligned inwidthcolumns^- the argument is center-aligned inwidthcolumns>- the argument is right-aligned inwidthcolumns
assert_eq!("00000110", format!("{:0>8}", "110"));
// |||
// ||+-- width
// |+--- align
// +---- fill
Смотрите также:
В качестве альтернативы ответу Шепмастера, если вы фактически начинаете с числа, а не строки, и хотите отображать его как двоичный, способ форматирования:
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);