• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.
  • The forums have been upgraded with support for dark mode. By default it will follow the setting on your system/browser. You may override it by scrolling to the end of the page and clicking the gears icon.

C# to VB translation problem?

jchunn

New Member
Joined
Mar 12, 2008
Messages
2 (0.00/day)
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.
 
Last edited:
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
Code:
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.
 
Back
Top