keelar keelar - 1 month ago 11
C++ Question

Best way to convert uint64_t to jlong

I am writing a JNI code and encounter a situation where I will need convert uint64_t to jlong, and here's my current way to convert uint64_t to jlong:

jlong uint64_t_to_jlong (uint64_t value) {
if (value > std::numeric_limits<jlong>::max()) {
return std::numeric_limits<jlong>::max();
}
return static_cast<jlong>(value);
}


And this is obviously not a perfect approach as it can't really convert the value correctly when
value > std::numeric_limits<jlong>::max()
. However, directly returning
static_cast<jlong>(value)
doesn't sound a good approach to me either, as in the Java side we will receive negative value.

Can I know whether there exist better approach which can handle all cases smoothly and correctly?

Answer

As suggested in the comment by Louis, one way to handle it in Java 8 is to simply cast uint64_t to jlong in the C++ side, then use the set of unsigned operation provided by Java 8 such as Long.compareUnsigned() to do the necessary operation:

public static int compareUnsigned(long x, long y)
Compares two long values numerically treating the values as unsigned.

Google Guava's unsigned libraries can also achieve this in case Java 8 is not used.