Convert an integer to a binary string with leading zeros

前端 未结 6 2083
醉酒成梦
醉酒成梦 2021-02-05 01:24

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

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

it returns 11, but I need 0011

6条回答
  •  深忆病人
    2021-02-05 02:05

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

    3 = 20 * 1 + 21 * 1

    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
    

提交回复
热议问题