tags:

views:

138

answers:

6
+2  Q: 

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...)

+7  A: 

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...

Macmade
A: 

whatever_your_int_var_name_is = (int)whatever_your_uint64_t_var_name_is;

Adam Shiemke
+2  A: 

Note that java does not support unsigned types. The closest type in java will be long, since it also has 64 bits. Casting uint64 to long doesn't loose data because the number of bits are the same, but large values will be displayed as negative numbers then.

codymanix
+4  A: 

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 */
R..
+1  A: 

If you are writing JNI wrappers, the best match for uint64_t is long, not int. Even then you will lose accuracy, as Java doesn't have unsigned types (hence the u), and you need to be prepared to check the sign of the value.

Tassos Bassoukos
is there a way to store the uint64_t of C in java? In my case, the uint64_t is always a positiv number
mkn
If you want that uint64_t *just* to pass it to java as an identifier (and back to C), use a long - there won't be a degradation, but values larger than 2^63 will become negative - long has 64 bits by definition, but uses a bit as the sign.
Tassos Bassoukos
A: 

hm... I have method in C which returns a page_ID which is an uint64_t number. Now I need to store that number in a Java HashMap. So what's the best way to store that uint64_t in the Java HashMap? The problem is, that when I do a lookup operation, I need to take that specific value in the HashMap and cast it back to an uint64_t so that I can call a function in the C code, which expects a uint64_t as the argument.

P.S. i've done it with jlong pid = (jlong) pid_in_uint64_t; so far so good...

mkn
`jlong` seems to fit your purpose just fine.
Michael Foukarakis