1

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
}   
  1. Why can't BitArray copy to an unsigned int?
  2. 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#

Community
  • 1
  • 1
JayE
  • 11
  • 4

2 Answers2

1
  1. Copying a BitArray to an UInt32 is not supported by the implementation, according to documentation which is quite recent (10/2016):

The specified array must be of a compatible type. Only bool, int, and byte types of arrays are supported.

  1. The most significant bit in an int is used to store the sign. To tell the compiler that you intend a numeric literal to be unsigned, use the U suffix: 1U << 31
Community
  • 1
  • 1
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
0

The problems have been explained, but it hasn't been made explicit what you do about so, for completeness:

You should use CopyTo into an int[], then convert your int to an uint, like this (not tested)

int[] temp = new int[1];
bits.CopyTo(temp);
uint asUint = unchecked((uint)temp[0]);

The unchecked is kind of silly, but you seem to have switched on the "check arithmetic by default" checkbox (otherwise (uint)(1 << i) would have worked - there is no inherent problem with that, it's only dangerous in a checked context).

Or even better than the above, if you BitArray is short you can avoid using it altogether and just always work with the bits of the uint.

harold
  • 61,398
  • 6
  • 86
  • 164