If I want to convert 4 bytes into an int, I can do this:
byte[] b = BitConverter.GetBytes(i1);
int i2 = BitConverter.ToInt32(b,0);
int i3 = b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24);
and then i1,i2,i3 will all equal.
but how do I do the same for a uint? This:
uint u1 = uint.MaxValue-1000;
byte[] b = BitConverter.GetBytes(u1);
uint u2 = BitConverter.ToUInt32(b,0);
uint u3 = (uint)(b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24));
results in a overlflow for large uints.
It would only throw that exception if in a checked context. See: http://msdn.microsoft.com/en-us/library/y3d0kef1(v=vs.80).aspx.
No exception:
exception:
no exception
Make sure you’re not compiling with the /checked option.
The exception is thrown by casting from int to uint. Using the shift operator on the bytes (the line with uint u3 = …) implicitly cast them to int. A uint with the MSB on (“1”) is a negative int which is out of range for uint. Using int causes no such exception because there is no explicit cast which might elicit an overflow exception.