Implicit Numeric Conversions – BitArray Gotcha!

I’ve recently been working on a library to query DNS servers and parse the response into an object. When creating the packet for transmit, there’s a section needed in the header called “Parameters” which represents various options of the DNS query spread across 2x Bytes (16 Bits). Most of the parameters are boolean with the exception of Opcode and Reply code which are both 4 bits due to needing multiple answers (up to 15 answers each).

I felt the best way to create and manipulate this data would be by utilising an old collection (.NET 1.1) called BitArray.  The BitArray collection is extremely easy to work with and accepts a variety of parameters for initialising from Bytes to Bits. You can pass in a Byte array for initialisation which the class then converts to Bits and your data can be manipulated….all good so far. The one thing which I didn’t realise and just presumed is that it would also accept a single Byte as the parameter (big mistake).

So my code looked something similar to this:

var bytesData = new[] {0xc4, 0x6e}; 
BitArray arr = new BitArray(bytesData[0]);

and ended up with this result:

So instead of having a BitArray collection with a count of 8 which represented the first Byte in the Byte array, I ended up implicitly passing the value of that Byte as an Integer due to the wonderful world of Implicit Numeric Conversion.  As you’ve probably guessed, this caused serious packet malformation with one DNS server blocking me during testing. It was only when I finally interrogated the MSDN documentation for the BitArray class that I noticed that it does not have a constructor parameter for Byte. It will only accept a single Byte by passing it inside an array.

I cant really see this happening on a daily basis for most developers but I think it’s definitely worth keeping in mind especially if working with Bytes and unfamiliar library.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.