如何从字节数组中获取某个位置的值?

时间:2013-12-12 22:01:56

标签: c# byte bits

byte[] sample = new byte[]{10,20,30};

- 该值为6位,从第三位(从右到左)开始

new byte [] {10,20,30}看起来像“00001010 00010100 00011110”(应按字节顺序排列) 所以我需要“00001010 00010100 * 000111 * 10” - 我的价值是7

基于帮助的解决方案(通过 Yaur 回答1),只是改变位方向

   public static bool GetValue(byte[] data, int position)
        {
            var bytePos = data.Length - 1 - position / 8;//right -> left
            //var bytePos = position / 8;//left -> right
            var bitPos = position % 8;

            return ((data[bytePos] & (1 << bitPos)) != 0);//right -> left
            //return ((data[bytePos] & (1 << (7 - bitPos))) != 0); //left -> right
        }

        public static long GetValue(byte[] data, int position, int length)
        {
            if (length > 62)
            {
                throw new ArgumentException("not going to work properly with 63 bits if the first bit is 1");
            }
            long retv = 0;
            for (int i = position + length - 1; i > position - 1; i--)
            //for(int i = position;i<position+length;i++)//left -> right
            {
                if (GetValue(data, i)) retv |= 1;
                retv = retv << 1;
            }
            retv = retv >> 1;
            return retv;
        }

1 个答案:

答案 0 :(得分:3)

这适用于大多数输入:

public bool GetValue(byte[] data, int position) 
{
    var bytePos = position / 8;
    var bitPos = position % 8;
    return ((data[bytePos] & (1 << bitPos))!=0)
    // depending on the order in which you expect the bits you might need this instead
    //return ((data[bytePos] & (1 << (7-bitPos)))!=0)

}

public long GetValue(byte[] data, int position, int length) 
{
    if(length > 62)
    {
        throw new ArgumentException("not going to work properly with 63 bits if the first bit is 1");
    }
    long retv=0;
    for(int i = position;i<position+length;i++)
    {
         if(GetValue(data,i)
         {
             retv |=1;
         }
         retv = retv << 1;
    }
    retv = retv >> 1;
}