I am trying to convert 32 bits in a BitArray to a UInt32 in a 32bit c# NET4.0 app in Win7 64bit.
I have tried two techniques but both throw an exception.
When using CopyTo, it throws this: System.ArrayTypeMismatchException: Source array type cannot be assigned to destination array type.
BitArray newBits = new BitArray(32);
// (modify bits...)
UInt32[] intArray = new UInt32[1];
newBits.CopyTo(intArray, 0); // < crash
When manually setting the bits, it throws this when it gets to the 32nd bit (when i = 31): System.OverflowException: Arithmetic operation resulted in an overflow.
BitArray newBits = new BitArray(32);
// (modify bits...)
UInt32 res = 0;
for (int i = 0 ; i < newBits.Length ; i++)
{
//Debug("i="+i+", "+newBits.Length);
if (newBits[i]) res |= (UInt32)(1 << i); // < crash when i reaches 31
}
- Why can't BitArray copy to an unsigned int?
- Why does '1 << i' fail when i = 31 in a 32bit variable?
(sorry for the duplicate question, I tried commenting in the other post but I need 50 reputation) Converting a BitArray in to UInt32 C#