Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uint64_t to int

I'm writing a java binding for a C code and I'm not really familiar with C.

I have a uint64_t and need to cast it to a int. Does anyone know how to do that? (My binding returns then a jint...)

like image 650
mkn Avatar asked Nov 27 '25 16:11

mkn


2 Answers

The short answer:

uint64_t foo;
int bar;
bar = foo;

Technically this has undefined behavior if the value of foo does not fit in an int. In practice, it will always simply truncate the upper bits. If you want to be more correct, then:

if (foo-INT_MIN <= (uint64_t)INT_MAX-INT_MIN)
    bar = foo;
else
    /* error case here */
like image 142
R.. GitHub STOP HELPING ICE Avatar answered Nov 29 '25 10:11

R.. GitHub STOP HELPING ICE


Usually, using an exact width integer like 'uint64_t' is for a good reason. If you cast it to an int, which may not be 64bits long, you may have serious problems...

like image 42
Macmade Avatar answered Nov 29 '25 12:11

Macmade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!