如何从字节数组中获取特定位置的位值

本文关键字:定位 位置 获取 字节 字节数 数组 | 更新日期: 2024-09-27 10:09:02

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

如何从字节数组中获取特定位置的位值

这应该适用于大多数输入:

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