When the int variable is more than 10 digits, an error occurs and the number becomes negative.
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
CodePudding user response:
tl;dr
Simply use ulong
instead of int
for unixtimeOnline
ulong unixtimeOnline = itemsData2["lastUpdated"];
What happened?
As was already mentioned int
(or also System.Int32
) has 32 bits.
The int.MaxValue
is
2147483647
no int
can be higher than that. What you get is basically a byte overflow.
From the JSON.Parse
I suspect you are using 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; }
which uses AsInt
public virtual int AsInt { get { return (int)AsDouble; } set { AsDouble = value; } }
which is a problem because a double
can hold up to
so when you simply do
double d = 2147483648.0;
int example = (int)d;
you will again get
-2147483648
What you want
You want to use a type that supports larger numbers. Like e.g.
long
: goes up to9,223,372,036,854,775,807
and is actually what system time ticks are usually stored as (see e.g.
DateTime.Ticks
or actually since your time is probably never negative anyway directly use the unsigned ones
ulong
: goes up to18,446,744,073,709,551,615
Solution
Long store short: There are implicit conversion for the other numeric values so all you need to do is use
ulong unixtimeOnline = itemsData2["lastUpdated"];
and it will use AsUlong
instead
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(); } }
CodePudding user response:
As the comment says you will need to use a long
variable type