73

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

  • "110" = "00000110"

  • "11110000" = "11110000"

I have tried to use the format! macro but it only pads to the right with space:

format!("{:08}", string);
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
SeaEyeHay
  • 913
  • 2
  • 7
  • 7

2 Answers2

142

The fmt module documentation describes all the formatting options:

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

See also:

vallentin
  • 23,478
  • 6
  • 59
  • 81
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 3
    It would be nice to see here succinctly how to specify fill, width, alignment, and the user-specified variable in one go as variables to `format!` – Evan Carroll Sep 14 '21 at 05:54
21

As an alternative to Shepmaster's answer, if you are actually starting with a number rather than a string, and you want to display it as binary, the way to format that is:

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);
Peter Hall
  • 53,120
  • 14
  • 139
  • 204