Search code examples
c#mpeg2-ts

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


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??


Solution

  • 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.