Max HEX value for long type

前端 未结 4 1891
情书的邮戳
情书的邮戳 2021-01-21 23:38

I have ported Java code to C#. Could you please explain why I have compile-time error in the follow line (I use VS 2008):

    private long l = 0xffffffffffffffff         


        
4条回答
  •  花落未央
    2021-01-21 23:44

    0xffffffffffffffff is larger than a signed long can represent.

    You can insert a cast:

     private long l = unchecked( (long)0xffffffffffffffffL);
    

    Since C# uses two's complement, 0xffffffffffffffff represents -1:

    private long l = -1;
    

    Or declare the variable as unsigned, which is probably the cleanest choice if you want to represent bit patterns:

    private ulong l = 0xffffffffffffffffL;
    private ulong l = ulong.MaxValue;
    

    The maximal value of a singed long is:

    private long l = 0x7fffffffffffffffL;
    

    But that's better written as long.MaxValue.

提交回复
热议问题