簡體   English   中英

如何從字節數組中的某個位置獲取位的值?

[英]How to get the value of a bit at a certain positions from a byte array?

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

-值是6位,從第三位開始(從右到左)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM