Max HEX value for long type

血红的双手。 提交于 2019-12-02 02:04: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 = 0xffffffffffffffffL; // 16 'f' got here

Cannot convert source type ulong to target type long

I need the same value here as for origin Java code.


回答1:


Assuming you aren't worried about negative values, you could try using an unsigned long:

private ulong l = 0xffffffffffffffffL;

In Java the actual value of l would be -1, because it would overflow the 2^63 - 1 maximum value, so you could just replace your constant with -1.




回答2:


Java doesn't mind if a constant overflows in this particular situation - the value you've given is actually -1.

The simplest way of achieving the same effect in C# is:

private long l = -1;

If you want to retain the 16 fs you could use:

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

If you actually want the maximum value for a signed long, you should use:

// Java
private long l = Long.MAX_VALUE;
// C#
private long l = long.MaxValue;



回答3:


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.




回答4:


You could do this:

private long l = long.MaxValue;

... but as mdm pointed out, you probably actually want a ulong.

private ulong l = ulong.MaxValue;


来源:https://stackoverflow.com/questions/8825380/max-hex-value-for-long-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!