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

问题描述 投票:36回答:4

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

Convert.ToString(MyVeryOwnByte, 2);

但是当字节在开始时为0时,那些0被引用。例:

MyVeryOwnByte = 00001110 // Texbox shows -> 1110
MyVeryOwnByte = 01010101 // Texbox shows -> 1010101
MyVeryOwnByte = 00000000 // Texbox shows -> <Empty>
MyVeryOwnByte = 00000001 // Texbox shows -> 1

我想显示所有8位数字。

c# .net string byte bits
4个回答
68
投票
Convert.ToString(MyVeryOwnByte, 2).PadLeft(8, '0');

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


11
投票

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

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

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

如果您想要输出“00011011”,请使用如下函数:

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

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

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

1
投票

用零填充字符串。在这种情况下,它是PadLeft(length, characterToPadWith)。非常有用的扩展方法。 PadRight()是另一种有用的方法。


0
投票

您可以创建一个扩展方法:

public static class ByteExtension
{
    public static string ToBitsString(this byte value)
    {
        return Convert.ToString(value, 2).PadLeft(8, '0');
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.