Manipulating Bits and Bytes Using C#

Recently I was working on detection of MP3 file format when a user uploads a file to a web site. Part of the detection was to look for ID3 header and figuring out what flags were set in header. The format specification tells you at what bit locations to check for what flags. This meant that you will need some mechanism to figure out what bits are set with in a byte. If you are seasoned C/C++ developer, you pretty much know that this meant that doing some low level bit shift operations on that byte to rotate through them to check which bit is set and which is not set. So if you will write that code in C#, it will look like snippet below.

static void ConvertToBinaryFormat(byte n)
 var flags = new BitArray(8);
 var counter = 8;
 var idx = 0;
 while(counter > 0)
  flags.Set(idx++, ((n & 1) == 1));
  n >>= 1;

static void PrintBitArray(BitArray ba)
 for(int i = ba.Length-1; i >= 0; i--)
 Console.Write("{0}", ba[i] ? 1 : 0);

Looking at the code, you are already saying that I have already used BitArray class object in this function. Then why am I doing all the low level operations. I intentionally introduced BitArray here to demonstrate that you really do not need to do all the low level operations to check what bits are set. BitArray class already does that for you. Following one line of code does the same thing that I did by doing some bit shifting.

var newFlags = new BitArray(new byte[] {20});

If you look at PrintBitArray method, you will notice that it is using reverse loop to print each bit. When bit shit operation is being done, bit array gets filled from right to left. This means that higher order bits get pushed low. And BitArray class does the same thing. So you will have to access the array from bottom.




15.9 °C / 60.6 °F

weather conditions Clouds

Monthly Posts

Blog Tags