What I am creating is essentially a binary clock face with touch input for setting values as well as displaying - so I need to convert both ways between an int and a binary sequence in a BitArray.
I cobbled this together (borrow and modifying a bit from a couple different examples I found):
public class BinaryConverter
{
public static BitArray ToBinary(int numeral)
{
BitArray binary = new BitArray(new int[] { numeral });
bool[] bits = new bool[binary.Count];
binary.CopyTo(bits, 0);
return binary;
}
public static int ToNumeral(BitArray binary, int length)
{
int numeral = 0;
for (int i = 0; i < length; i++)
{
if (binary[i])
{
numeral = numeral | (((int)1) << (length - 1 - i));
}
}
return numeral;
}
}
It isn't especially verbose, but in my head before I started it should have been a couple of lines per method, perhaps better leveraging some .NET classes like System.Convert (though, I can't quite see how to do that). Is there a cleaner way to do this? Do you have any other suggestions for improvement?