[英]When the int variable is more than 10 digits
当int变量超过10位时,会出错,数字变为负数。
为什么会发生这种情况,我该如何解决这个问题?
这是我的代码:
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
只需为unixtimeOnline
使用ulong
而不是int
ulong unixtimeOnline = itemsData2["lastUpdated"];
正如已经提到的int
(或System.Int32
)有32位。
2147483647
没有int
可以比那个更高。 你得到的基本上是字节溢出。
来自JSON.Parse
我怀疑你正在使用SimpleJson
如果你有
int unixtimeOnline = itemsData2["lastUpdated"];
它会隐含地使用
public static implicit operator int(JSONNode d) { return (d == null)? 0: d.AsInt; }
它使用AsInt
public virtual int AsInt { get { return (int)AsDouble; } set { AsDouble = value; } }
这是一个问题,因为double
可以承受
所以当你简单地做
double d = 2147483648.0;
int example = (int)d;
你会再次得到
-2147483648
您想要使用支持更大数字的类型。 像例如
long
:上升到
9,223,372,036,854,775,807
并且实际上是系统时间刻度通常存储为(参见例如DateTime.Ticks
或者实际上因为你的时间可能永远不会是负的所以直接使用无符号的
ulong
:上升到
18,446,744,073,709,551,615
Long store short:其他数值有隐式转换,所以你需要做的就是使用
ulong unixtimeOnline = itemsData2["lastUpdated"];
它将改用AsUlong
public static implicit operator ulong(JSONNode d) { return (d == null)? 0: d.AsULong; }
现在正确使用
public virtual ulong AsULong { get { ulong val = 0; if (ulong.TryParse(Value, out val)) return val; return 0; } set { Value = value.ToString(); } }
正如评论所说,您将需要使用long
变量类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.