views:

1134

answers:

4

If I have a VB.Net function that returns an Int32, but uses an unsigned int (UInt32) for calculations, etc. How can I convert a variable "MyUintVar32" with a value of say "3392918397 into a standard Int32 in VB.Net?

In c# if I just do a "return (int)(MyUintVar32);", I get -902048899, not an error.

I've tried several different methods. What is the difference in the way c# handles these conversions versus VB.Net?

A: 

It's not an optimal solution, but you can use BitConverter to get a byte array from the uint and convert the byte array to int.

Juanma
Which is an overcomplicated way of doing (int)MyUintVar32.
MusiGenesis
Thank-you. It is a bit ugly, but this is just what I needed. I did a poor job of stating problem, this was for a third party product that uses a crc32 checksum (and I didn't wnat to get a lot of comments on that). They provided the c# code for their checksum, but the customer HAS to have vb.net
APOD
@MusiGenesis. In the question he says that casting that way produces an errror in VB.NET
Juanma
+3  A: 

3392918397 is too big to fit into a signed 32-bit integer, that's why it is coming out negative, because the most significant bit of 3392918397 is set.

1100 1010 0011 1011 1101 0011 0111 1101

If you want to maintain integers of this proportion inside a signed integer type, you'll need to use the next size up, a 64-bit signed integer.

dreamlax
+1  A: 

You can't convert 3392918397 into an Int32 since that number is too large to fit in 31 bits. Why not just change the function to return a UInt32?

Adam Rosenfield
A: 

Or after doing the Uint32 work check it against MAXINT and 0.

If > MAXINT and < 0 then you're ok. If not you "overflowed" and should throw an exception.

I don't remember if MAXINT is defined. You can use: 2^31 - 1 instead.

jim