Convert an integer to a binary string with leading zeros

前端 未结 6 2080
醉酒成梦
醉酒成梦 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 01:52

    I've created a method to dynamically write leading zeroes

    public static string ToBinary(int myValue)
    {
          string binVal = Convert.ToString(myValue, 2);
          int bits = 0;
          int bitblock = 4;
    
          for (int i = 0; i < binVal.Length; i = i + bitblock)
          { bits += bitblock; }
    
          return binVal.PadLeft(bits, '0');
    }
    

    At first we convert my value to binary. Initializing the bits to set the length for binary output. One Bitblock has 4 Digits. In for-loop we check the length of our converted binary value und adds the "bits" for the length for binary output.

    Examples: Input: 1 -> 0001; Input: 127 -> 01111111 etc....

提交回复
热议问题