开发者

uint64_t to int

I'm writing a java binding for a C code and I'm no开发者_如何学编程t 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...)


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


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 */


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.


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.


whatever_your_int_var_name_is = (int)whatever_your_uint64_t_var_name_is;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜