Convert an integer to a binary string with leading zeros

前端 未结 6 2084
醉酒成梦
醉酒成梦 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:17

    Just what Soner answered use:

    Convert.ToString(3, 2).PadLeft(4, '0') 
    

    Just want to add just for you to know. The int parameter is the total number of characters that your string and the char parameter is the character that will be added to fill the lacking space in your string. In your example, you want the output 0011 which which is 4 characters and needs 0's thus you use 4 as int param and '0' in char.

提交回复
热议问题