How to store 13-bit structure?

220 views Asked by At

I want to create a class that represents an MPEG 2 Transport Stream packet. I want to have a class property that stores the 13 bit PID value? What would be the best data type? Would you use a mask to store this value? I'm thinking I should just convert the value to an int...that would be easiest solution right? How do you store different numbers of bits that are not a byte?

public class Mpeg2TransportPacket
{
    byte SyncByte { get; set; }
    bool TransportErrorIndicator { get; set; }
    bool PayloadUnitStartIndicator { get; set; }
    bool TransportPriority { get; set; }

    int PID { get; set; }
}
2

There are 2 answers

0
Dweeberly On BEST ANSWER

For a single value like that I would think that System.Int16 would be fine.

If you need to mask out 13 bits you would use a mask and & operation

var mask = 0b0001_1111_1111_1111; // c# v7.0 binary literal, low order bits
var pid = value & mask; // value is what you are applying the mask to
0
Matteo Marciano - MSCP On

I would store the PID into a BitArray class and then map each boolean property of your class to write/read from such class

For better performances, use BitVector32.