PDA

View Full Version : C# to VB translation problem?


jchunn
03-12-2008, 06:15 AM
In C#, this works, but I don't understand why:

int i = ( int ) ( 0xff000000 | (r << 16) | (g << 8) | b );

Shouldn't that cause an overflow?

In the debugger, this:
( 0xff000000 | (r << 16) | (g << 8) | b )
equals this: 4278190080

But this:
( int ) ( 0xff000000 | (r << 16) | (g << 8) | b )
equals this: -16777216

What is going on there? The VB translation would be this:

Dim i as Integer = CType((4278190080 Or (r << 16) Or (g << 8) Or b), Integer)
But that returns an overflow error, since obviously the result (4278190080) is too large for an Integer, and unlike C#, it does not magically turn into -16777216.

Any help would be greatly appreciated.

Edit: r, g, and b all = 0 in this example.

Kreij
03-12-2008, 12:41 PM
In C# there are two keywords "checked" and "unchecked".
Unchecked turns off overflow checking. (Checked is on by default)

My compiler throws an error unless I wrap the statement in an unchecked condition

unchecked
{
int i = (int)(0xff000000 | (0<<16) | (0<<8) | 0);
}

In which case it returns the same negative value that you get.

If you are not using the unchecked keyword, make sure that it is not being shut off globally in your compiler options or environment configuration.

jchunn
03-12-2008, 02:21 PM
That is the answer... thank you very much! Problem solved.