I am currently converting some OpenCV code from C++ to Java. I can't use JavaCV, as we need the conversion in native Java, not a JNA. At one point in the code, I get the following assignment:
dst[x] = (uchar)(-(kHit >= kForeground));
Where dst
is uchar*
, kHit
and kForeground
are int
s.
I've been unable to find anything about how this works, and Java will not recognize it as an operation. There is an operation on these two variables at another point in the code, and it stores one of two values: 255 or 0.
The code in question comes from opencv/video/src/bgfg_gaussmix.cpp
.
The - (unary minus) operator negates the value of the operand. The operand can have any arithmetic type. The result is not an lvalue. For example, if quality has the value 100 , -quality has the value -100 .
These are the type of operators that act upon just a single operand for producing a new value. All the unary operators have equal precedence, and their associativity is from right to left. When we combine the unary operator with an operand, we get the unary expression.
The unary operator is used to change the sign of any positive value to a negative value. It means it changes the positive number to the negative, and a negative number becomes the positive number using the unary minus operator. Example 1: #include <stdio.
The unary minus is used to show a negative number. For example: -97.34. means "negative ninety seven point thirty four." The subtraction operator is used to show a subtraction of one number from another. For example: 95 - 12.
In C++ a boolean expression produces one of two values - 0
or 1
. When you apply the unary minus -
to the result, you get 0
or -1
. When you re-interpret -1
as uchar
, you get 255
.
You can convert this expression to Java with a conditional:
dst[x] = (kHit >= kForeground) ? 255 : 0;
Because of branching, it is not going to be as fast as the original one. There's little you can do about the speed of it, however, as Java lacks abilities to re-interpret boolean values as numerics.
kHit >= kForeground
returns either true
or false
, which in C++ sort of means 1
or 0
. The minus in front transforms this to -1
or 0
. The cast to uchar
((uchar)
) returns 0
for 0
and wraps to 255
for the negative -1
.
Following Konrad's comment, I'm also skeptical this is well defined. It is well defined, but it's still an awful piece of code in terms of readability. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With