1. Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

C# to VB translation problem?

Discussion in 'Programming & Webmastering' started by jchunn, Mar 12, 2008.

  1. jchunn New Member

    Joined:
    Mar 12, 2008
    Messages:
    2 (0.00/day)
    Thanks Received:
    0
    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: Mar 12, 2008
  2. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.12/day)
    Thanks Received:
    5,615
    Location:
    Cheeseland (Wisconsin, USA)
    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.
    jchunn says thanks.
  3. jchunn New Member

    Joined:
    Mar 12, 2008
    Messages:
    2 (0.00/day)
    Thanks Received:
    0
    That is the answer... thank you very much! Problem solved.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guest)

Share This Page