如何用零填充二进制字符串?

Rya*_*hel 10 c# string format binary formatting

string binary = Convert.ToString(15, 2);

Console.WriteLine("{0}", binary);
Run Code Online (Sandbox Code Playgroud)

打印:

1111

我想要它打印 00001000

因为数据类型是字符串而不是整数,所以我不能这样做:

Console.WriteLine("{0:00000000}", binary);
Run Code Online (Sandbox Code Playgroud)

Bal*_*a R 20

Console.WriteLine( binary.PadLeft(8, '0'));
Run Code Online (Sandbox Code Playgroud)


Bry*_*ong 8

你可以尝试这个:

Convert.ToString(15, 2).PadLeft(8, '0');

它应该给你 00001111