C#: assign 0xFFFFFFFF to int

后端 未结 3 762
醉酒成梦
醉酒成梦 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 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.

提交回复
热议问题