How to get bit values from byte array using shifting with 32 bit big endian mask in C#

871 views Asked by At

I have a four byte array (which represents an MPEG TS packet header) and I want to get PID value which is 13 bits starting from bit 12 to 24 (in bold). Wikipedia says the PID value has a 32-bit Big Endian Mask... what does that mean?

0100 0111 0000 0101 0011 0100 0001 1101

I understand that the first byte or eight bits is 0x47 because there are 8 bits...

128 64 32 16 8 4 2 1

0 1 0 0 0 1 1 1

0x47 is 71 or 64 + 4 + 2 + 1...

How do you parse bit values inside the byte array that are not 8 bits and/or embedded across bytes??

2

There are 2 answers

0
mbd On BEST ANSWER

first taken from Wikipedia https://en.wikipedia.org/wiki/Endianness#Big

The most significant byte (MSB) value, 0Ah, is at the lowest address. The other bytes follow in decreasing order of significance. This is akin to left-to-right reading in hexadecimal order.

Therefore your bits in the array are in the right order, you just need the value. You can create an integer by taking the first byte (ignoring the first 3 bits), shifting it by 8 bits and then adding the second byte.

byte[] packet = new byte[4];
int value = ((0x1F & packet[1]) << 8) | packet[2];

Which gives 0x0534 (101 0011 0100) for your example. Then you can compare this value to the ones listed on Wikipedia.

0
InGeek On

This would work for any size of byte array:

public static bool CheckIfMaskBitIsSet(byte[] mask, int bit)
        { 
            int bitPerByte = bit % 8;
            int byteIndex = bit > 0 ? (bit / 8) : 0;
            if(mask.Length>byteIndex)
                return ((mask[byteIndex] >> bitPerByte) & 1) == 1;
            return false;
        }