Convert an integer to a binary string with leading zeros

前端 未结 6 2094
醉酒成梦
醉酒成梦 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条回答
  •  猫巷女王i
    2021-02-05 02:07

    public static String HexToBinString(this String value)
    {
            String binaryString = Convert.ToString(Convert.ToInt32(value, 16), 2);
            Int32 zeroCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(binaryString.Length) / 8)) * 8;
    
            return binaryString.PadLeft(zeroCount, '0');
    }
    

提交回复
热议问题