如何从Byte返回位

时间:2010-11-15 03:05:59

标签: c#

似乎是基本的,但我不知道如何从一个字节中获取每个位。谢谢你的帮助

5 个答案:

答案 0 :(得分:3)

这些位从右到左“编号”为0到7。所以要获得第5位,你可以使用byte & (1<<5)
我确信有更清楚的解释这个&gt; _&gt;

的方法

编辑:这可以在IF语句中使用,但如果您只想要1或0,请使用winwaed的解决方案。

答案 1 :(得分:2)

尝试使用BitArray

byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
BitArray myBA3 = new BitArray( myBytes );

答案 2 :(得分:2)

正如RyuuGan已发布的那样,你应该使用BitArrary。您只需通过调用带有所需元素的构造函数将数据放入其中。

byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
BitArray bitArray = new BitArray( myBytes );

之后,实例有一些有趣的属性可以轻松访问每个位。首先,您可以调用索引运算符来获取或设置每个位的状态:

bool bit = bitArray[4];
bitArray[2] = true;

你也可以通过使用foreach循环(或你喜欢的任何LINQ东西)来枚举所有位。

foreach (var bit in bitArray.Cast<bool>())
{
    Console.Write(bit + " ");
}

要从位返回某些特定类型(例如int)有点棘手,但使用这种扩展方法非常简单:

public static class Extensions
{
    public static IList<TResult> GetBitsAs<TResult>(this BitArray bits) where TResult : struct
    {
        return GetBitsAs<TResult>(bits, 0);
    }

    /// <summary>
    /// Gets the bits from an BitArray as an IList combined to the given type.
    /// </summary>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="bits">An array of bit values, which are represented as Booleans.</param>
    /// <param name="index">The zero-based index in array at which copying begins.</param>
    /// <returns>An read-only IList containing all bits combined to the given type.</returns>
    public static IList<TResult> GetBitsAs<TResult>(this BitArray bits, int index) where TResult : struct
    {
        var instance = default(TResult);
        var type = instance.GetType();
        int sizeOfType = Marshal.SizeOf(type);

        int arraySize = (int)Math.Ceiling(((bits.Count - index) / 8.0) / sizeOfType);
        var array = new TResult[arraySize];

        bits.CopyTo(array, index);

        return array;
    }
}

有了这个,您只需使用以下一行代码即可摆脱它:

IList<int> result = bitArray.GetBitsAs<int>();

答案 3 :(得分:1)

使用

 Convert.ToString (value, 2)

答案 4 :(得分:1)

使用位移。

EG。比特3:b =(值>&gt; 3)&amp; 1;

决赛和掩码位1。 如果你想要布尔值,只需将上面的值(==)与值1进行比较。