将整数转换为带有前导零的二进制字符串

问题描述:

我需要将int转换为bin并添加额外的位.

I need to convert int to bin and with extra bits.

string aaa = Convert.ToString(3, 2);

它返回11,但是我需要001100000011.

it returns 11, but I need 0011, or 00000011.

如何完成?

11二进制表示形式 3.此值的二进制表示形式是2位.

11 is binary representation of 3. The binary representation of this value is 2 bits.

3 = 2 0 * 1 + 2 1 * 1

3 = 20 * 1 + 21 * 1

您可以使用 String.PadLeft(Int, Char) 方法添加这些零.

You can use String.PadLeft(Int, Char) method to add these zeros.

Convert.ToString(3, 2).PadLeft(4, '0') // 0011
Convert.ToString(3, 2).PadLeft(8, '0') // 00000011