[英]When the int variable is more than 10 digits
When the int variable is more than 10 digits, an error occurs and the number becomes negative.当int变量超过10位时,会出错,数字变为负数。
Why is this happening and how can I solve the problem?为什么会发生这种情况,我该如何解决这个问题?
This is my code:这是我的代码:
UnityWebRequest www = new UnityWebRequest("https://api.hypixel.net/skyblock/bazaar");
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
JSONNode itemsData = JSON.Parse(www.downloadHandler.text);
unixtimeOnline = itemsData2["lastUpdated"];
Debug.Log(unixtimeOnline);
// output -2147483648
Simply use ulong
instead of int
for unixtimeOnline
只需为
unixtimeOnline
使用ulong
而不是int
ulong unixtimeOnline = itemsData2["lastUpdated"];
As was already mentioned int
(or also System.Int32
) has 32 bits.正如已经提到的
int
(或System.Int32
)有32位。
The int.MaxValue
is int.MaxValue
是
2147483647
no int
can be higher than that.没有
int
可以比那个更高。 What you get is basically a byte overflow .你得到的基本上是字节溢出。
From the JSON.Parse
I suspect you are usingSimpleJson
来自
JSON.Parse
我怀疑你正在使用SimpleJson
and if you have如果你有
int unixtimeOnline = itemsData2["lastUpdated"];
it will implicitly use它会隐含地使用
public static implicit operator int(JSONNode d) { return (d == null)? 0: d.AsInt; }
public virtual int AsInt { get { return (int)AsDouble; } set { AsDouble = value; } }
which is a problem because a double
can hold up to这是一个问题,因为
double
可以承受
so when you simply do所以当你简单地做
double d = 2147483648.0;
int example = (int)d;
you will again get你会再次得到
-2147483648
You want to use a type that supports larger numbers.您想要使用支持更大数字的类型。 Like eg
像例如
long
: goes up to long
:上升到
9,223,372,036,854,775,807
and is actually what system time ticks are usually stored as (see eg DateTime.Ticks
并且实际上是系统时间刻度通常存储为(参见例如
DateTime.Ticks
or actually since your time is probably never negative anyway directly use the unsigned ones或者实际上因为你的时间可能永远不会是负的所以直接使用无符号的
ulong
: goes up to ulong
:上升到
18,446,744,073,709,551,615
Long store short: There are implicit conversion for the other numeric values so all you need to do is use Long store short:其他数值有隐式转换,所以你需要做的就是使用
ulong unixtimeOnline = itemsData2["lastUpdated"];
and it will use AsUlong
instead它将改用
AsUlong
public static implicit operator ulong(JSONNode d) { return (d == null)? 0: d.AsULong; }
which now correctly uses现在正确使用
public virtual ulong AsULong { get { ulong val = 0; if (ulong.TryParse(Value, out val)) return val; return 0; } set { Value = value.ToString(); } }
As the comment says you will need to use a long
variable type正如评论所说,您将需要使用
long
变量类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.