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

前端 未结 4 1067
别跟我提以往
别跟我提以往 2021-01-19 00:55

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 fo

4条回答
  •  醉话见心
    2021-01-19 01:07

    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.

提交回复
热议问题