C#: assign 0xFFFFFFFF to int

后端 未结 3 729
醉酒成梦
醉酒成梦 2020-12-30 00:34

I want to use HEX number to assign a value to an int:

int i = 0xFFFFFFFF; // effectively, set i to -1

Understandably, compiler complains. Q

相关标签:
3条回答
  • 2020-12-30 00:46

    Give someone a fish and you feed them for a day. Teach them to pay attention to compiler error messages and they don't have to ask questions on the internet that are answered by the error message.

    int i = 0xFFFFFFFF; 
    

    produces:

    Cannot implicitly convert type 'uint' to 'int'. An explicit conversion exists 
    (are you missing a cast?)
    

    Pay attention to the error message and try adding a cast:

    int i = (int)0xFFFFFFFF; 
    

    Now the error is:

    Constant value '4294967295' cannot be converted to a 'int' 
    (use 'unchecked' syntax to override)
    

    Again, pay attention to the error message. Use the unchecked syntax.

    int i = unchecked((int)0xFFFFFFFF); 
    

    Or

    unchecked
    {
        int i = (int)0xFFFFFFFF; 
    }
    

    And now, no error.

    As an alternative to using the unchecked syntax, you could specify /checked- on the compiler switches, if you like to live dangerously.

    Bonus question:

    What makes the literal a uint in the first place?

    The type of an integer literal does not depend on whether it is hex or decimal. Rather:

    • If a decimal literal has the U or L suffixes then it is uint, long or ulong, depending on what combination of suffixes you choose.
    • If it does not have a suffix then we take the value of the literal and see if it fits into the range of an int, uint, long or ulong. Whichever one matches first on that list is the type of the expression.

    In this case the hex literal has a value that is outside the range of int but inside the range of uint, so it is treated as a uint.

    0 讨论(0)
  • You just need an unchecked cast:

    unchecked
    {
        int i =  (int)0xFFFFFFFF;
    
        Console.WriteLine("here it is: {0}", i);
    }
    
    0 讨论(0)
  • 2020-12-30 01:04

    The unchecked syntax seems a bit gar'ish (!) when compared to the various single-letter numerical suffixes available.

    So I tried for a shellfish:

    static public class IntExtMethods
    {
        public static int ui(this uint a)
        {
            return unchecked((int)a);
        }
    }
    

    Then

    int i = 0xFFFFFFFF.ui();
    

    Because the lake has more fish.

    Note: it's not a constant expression, so it can't be used to initialize an enum field for instance.

    0 讨论(0)
提交回复
热议问题