字节到二进制字符串C# - 显示全部8位数字

Hoo*_*och 37 .net c# string byte bits

我想在文本框中显示一个字节.现在我正在使用:

Convert.ToString(MyVeryOwnByte, 2);
Run Code Online (Sandbox Code Playgroud)

但是当字节在0开始时,那些0正在被诅咒.例:

MyVeryOwnByte = 00001110 // Texbox shows -> 1110
MyVeryOwnByte = 01010101 // Texbox shows -> 1010101
MyVeryOwnByte = 00000000 // Texbox shows -> <Empty>
MyVeryOwnByte = 00000001 // Texbox shows -> 1
Run Code Online (Sandbox Code Playgroud)

我想显示所有8位数字.

Wra*_*ath 68

Convert.ToString(MyVeryOwnByte, 2).PadLeft(8, '0');
Run Code Online (Sandbox Code Playgroud)

这将向左填充空白区域,并为"0",表示字符串中共有8个字符


Gab*_*abe 11

如何操作取决于您希望输出的外观.

如果您只想要"00011011",请使用以下功能:

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

如果您想要输出"000 11011 ",请使用如下函数:

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

如果你想要像"0001 1011"这样的输出,这样的函数可能会更好:

static string PadNibble(byte b)
{
    return Int32.Parse(Convert.ToString(b, 2)).ToString("0000 0000");
}
Run Code Online (Sandbox Code Playgroud)