Search code examples
c++unary-operator

How does the unary minus operator work on booleans in C++?


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

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.


Solution

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