[英]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.