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

前端 未结 4 1066
别跟我提以往
别跟我提以往 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 00:57

    What it basically does is following:

    kHit >= kForeground
    

    is an expression of type bool

    -(kHit >= kForeground)
    

    converts this bool into an int (based on true==1 and false==0) and negates it, which results in true==-1 and false==0.

    This is then converted into a uchar, which results in -1==255 and 0==0.

    It has to be noted that though seeming as using the underlying implementation details of the numbers, all those conversions are guaranteed by the C++ and C standards, as negative unsigned numbers are specified to behave according to twos-complement.

    But if Java doesn't support this, you can always replace it by a conditional assignment:

    dst[x] = (kHit>=kForeground) ? 255 : 0;
    

提交回复
热议问题