Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 654
Wraith967 Avatar asked Jul 18 '12 14:07

Wraith967


People also ask

What is unary minus in C?

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 .

What is the purpose of unary operator in C?

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.

What is unary operator in C give two examples of unary operators in C?

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.

What is unary subtraction?

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.


2 Answers

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.

like image 181
Sergey Kalinichenko Avatar answered Oct 16 '22 21:10

Sergey Kalinichenko


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. :)

like image 21
Luchian Grigore Avatar answered Oct 16 '22 21:10

Luchian Grigore