代码之家  ›  专栏  ›  技术社区  ›  ChiliYago

如何从字节返回位

c#
  •  2
  • ChiliYago  · 技术社区  · 15 年前

    看起来很基本,但我不知道如何从一个字节中获取每一位。谢谢你的帮助

    5 回复  |  直到 15 年前
        1
  •  2
  •   Oliver    15 年前

    正如Ryuugan已经发布的那样,你应该 BitArrary . 只需使用所需的元素调用构造函数,就可以将数据放入其中。

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

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

    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>();
    
        2
  •  3
  •   Niet the Dark Absol    15 年前

    位从右到左“编号”为0到7。所以为了得到第5位,你需要 byte & (1<<5)
    我相信有更清晰的方式来解释这一点。

    编辑:这将在 IF 语句,但如果您只需要1或0,请使用Winwaed的解决方案。

        3
  •  2
  •   RyuuGan    15 年前

    尝试使用 BitArray .

    byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
    BitArray myBA3 = new BitArray( myBytes );
    
        4
  •  1
  •   Fredou    15 年前

    使用

     Convert.ToString (value, 2)
    
        5
  •  1
  •   winwaed    15 年前

    使用位移位。

    例如,位3:b=(值>>3)&1;

    最后一个和屏蔽位1。 如果需要布尔值,只需将上面的(==)与值1进行比较。