Byte to Binary String C# - Display all 8 digits

前端 未结 4 945
刺人心
刺人心 2020-12-05 22:58

I want to display one byte in textbox. Now I\'m using:

Convert.ToString(MyVeryOwnByte, 2);

But when byte is has 0\'s at begining those 0\'s

相关标签:
4条回答
  • 2020-12-05 23:10

    How you do it depends on how you want your output to look.

    If you just want "00011011", use a function like this:

    static string Pad(byte b)
    {
        return Convert.ToString(b, 2).PadLeft(8, '0');
    }
    

    If you want output like "00011011", use a function like this:

    static string PadBold(byte b)
    {
        string bin = Convert.ToString(b, 2);
        return new string('0', 8 - bin.Length) + "<b>" + bin + "</b>";
    }
    

    If you want output like "0001 1011", a function like this might be better:

    static string PadNibble(byte b)
    {
        return Int32.Parse(Convert.ToString(b, 2)).ToString("0000 0000");
    }
    
    0 讨论(0)
  • 2020-12-05 23:14
    Convert.ToString(MyVeryOwnByte, 2).PadLeft(8, '0');
    

    This will fill the empty space to the left with '0' for a total of 8 characters in the string

    0 讨论(0)
  • 2020-12-05 23:17

    You can create an extension method:

    public static class ByteExtension
    {
        public static string ToBitsString(this byte value)
        {
            return Convert.ToString(value, 2).PadLeft(8, '0');
        }
    }
    
    0 讨论(0)
  • 2020-12-05 23:28

    Pad the string with zeros. In this case it is PadLeft(length, characterToPadWith). Very useful extension methods. PadRight() is another useful method.

    0 讨论(0)
提交回复
热议问题