Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to handle "long long int " in cJSON? #348

Closed
pukaifei opened this issue Apr 28, 2019 · 2 comments
Closed

how to handle "long long int " in cJSON? #348

pukaifei opened this issue Apr 28, 2019 · 2 comments
Labels

Comments

@pukaifei
Copy link

    cJSON *root_js = cJSON_CreateObject();
    cJSON_AddNumberToObject(root_js, "value", 1326545647980439);
    char *data = cJSON_Print(root_js);
    printf("%s\n", data);
    
    cJSON *value_js = cJSON_GetObjectItem(root_js, "value");
    int64_t value = value_js->valueint;
    int64_t value = value_js->valuedouble;

So, how to get "value" ?
The number is bigger than INT_MAX, "uint64_t value = value_js->valueint" will be wrong.
Use "uint64_t value = value_js->valuedouble" will have a type conversion. Is there any possiblity that type conversion will have some problem ?

So what is the right way to get int64_t value ? Thanks !

@FSMaxB
Copy link
Collaborator

FSMaxB commented Apr 30, 2019

There is no support for int64_t in C89, so cJSON doesn't support it. See #151 and #14.

You can use valuedouble to store up to 53 bit integers without loss of precision if you are using a system that uses IEEE 754 Double Precision Floating Point Numbers (which is almost every system out there).

valueint is only there for legacy purposes, if you use cJSON_SetNumberValue, valuedouble will be set to whatever you pass to it and valueint will be either the result of casting the double to int or INT_MAX, INT_MIN if the double is outside of the range of an int.

@FSMaxB FSMaxB closed this as completed Apr 30, 2019
@FSMaxB
Copy link
Collaborator

FSMaxB commented Apr 30, 2019

Same goes for cJSON_AddNumberToObject, but be careful because 1326545647980439 is an integer literal and will be truncated by the compiler, so you need to use 1326545647980439.0 (and since this number takes 51 bits, it will fit in IEEE754 doubles.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants