Fox
Fox

Reputation: 17

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

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

-the value is 6 bits and started from third bit (from right to left)

new byte[]{10,20,30} looks like "00001010 00010100 00011110" (should be in order like bytes order) so i need "00001010 00010100 *000111*10" -my value is 7

the solution based on help(answer 1 by Yaur), just bits direction changed

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

Upvotes: 0

Views: 1277

Answers (1)

Yaur
Yaur

Reputation: 7452

This should work for most inputs:

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

Upvotes: 3

Related Questions