如何返回从字节位 [英] How to return bits from Byte

查看:163
本文介绍了如何返回从字节位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好像小学,但我不知道如何从一个字节得到每一位。感谢您的帮助。

Seems elementary but I am not sure how to get each bit from a byte. Thanks for the help

推荐答案

由于RyuuGan已经发布,你应该用的 BitArrary 。你只要把其中的数据通过调用想要的元素构造。

As RyuuGan already posted you should go with the BitArrary. You just put the data in it by calling the constructor with the wanted elements.

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



之后的实例有一些有趣的特性方便地访问每一位。起初,你可以只调用索引操作者获取或设置每个位的状态:

Afterwards the instance has some interesting properties to easily access each bit. At first you can just call the index operator to get or set the state of each bit:

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



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

Also you can enumerate over all bits by just using a foreach loop (or any LINQ-stuff you like)

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

要得到位一些特定类型的背面(例如int)是有点麻烦,但很容易使用这个扩展方法:

To get back from the bits to some specific type (e.g. int) is a little bit trickier, but is quite easy using this extension methods:

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;
    }
}

通过这个地方,你可以摆脱它用一行代码:

With this in place you can just get out of it with this single line of code:

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

这篇关于如何返回从字节位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆