Convert an integer to a binary string with leading zeros

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

    You can use these methods:

    public static class BinaryExt
    {
        public static string ToBinary(this int number, int bitsLength = 32)
        {
            return NumberToBinary(number, bitsLength);
        }
    
        public static string NumberToBinary(int number, int bitsLength = 32)
        {
            string result = Convert.ToString(number, 2).PadLeft(bitsLength, '0');
    
            return result;
        }
    
        public static int FromBinaryToInt(this string binary)
        {   
            return BinaryToInt(binary);
        }
    
        public static int BinaryToInt(string binary)
        {   
            return Convert.ToInt32(binary, 2);
        }   
    }
    

    Sample:

    int number = 3; 
    string byte3 = number.ToBinary(8); // output: 00000011
    
    string bits32 = BinaryExt.NumberToBinary(3); // output: 00000000000000000000000000000011
    

提交回复
热议问题