24

How do I convert an unsigned int to jint? Do I have to convert it at all, or can I just return it without any special treatment? This is basically my code right now, but I can't test it, as I haven't setup JNI locally.

JNIEXPORT jint JNICALL
Java_test_test(JNIEnv* env, jobject obj, jlong ptr)
{
    MyObject* m = (MyObject*) ptr; 
    unsigned int i = m->get(); 
    return i; 
}
Shane Lu
  • 1,056
  • 1
  • 12
  • 21
Pedro
  • 4,100
  • 10
  • 58
  • 96

3 Answers3

21

In the general case, jint is equivalent to int, and so can hold about half the values of unsigned int. Conversion will work silently, but if a jint value is negative or if an unsigned int value is larger than the maximum value a jint can hold, the result will not be what you are expecting.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
  • 1
    I am storing only small numbers, that will never exceed the limits of a jint, so it should be fine. – Pedro Nov 04 '11 at 16:34
  • @Jonathan Once the value reaches half the capacity of an unsigned int, it will give a negative int due to how the types are implemented; small values are fine – Will03uk Nov 04 '11 at 23:42
  • Yes, I know how `int` works. I'm asking Pedro if his data includes negative numbers. – Jonathan Grynspan Nov 05 '11 at 00:41
11

jint is a typedef for int32_t so all the usual casting rules apply.

IronMensan
  • 6,761
  • 1
  • 26
  • 35
11

Depending on your compiler settings, there may or may not be a warning about mixing signed/unsigned integers. There will be no error. All the caveats from the answers above apply - unsigned int values of 0x80000000 (2,147,483,648) and above will end up as negative integers on the Java side.

If it's imperative that those large numbers are preserved in Java, use a jlong as a return datatype instead, and convert like this:

return (jlong)(unsigned long long)i;

The point is to first expand to 64 bits, then to cast away unsigned-ness. Doing it the other way around would produce a 64-bit negative number.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281