一元减号运算符如何在C ++中对布尔值进行运算? [英] How does the unary minus operator work on booleans in C++?

查看:61
本文介绍了一元减号运算符如何在C ++中对布尔值进行运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将一些OpenCV代码从C ++转换为Java.我不能使用JavaCV,因为我们需要使用本机Java(而不是JNA)进行转换.在代码的某一时刻,我得到了以下分配:

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));

其中 dst uchar * kHit kForeground int s

我一直找不到有关它如何工作的任何信息,Java不会将其识别为一种操作.在代码的另一点对这两个变量进行了运算,它存储了两个值之一:255或0.

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.

有问题的代码来自 opencv/video/src/bgfg_gaussmix.cpp .

推荐答案

在C ++中,布尔表达式产生两个值之一- 0 1 .将一元减-应用于结果时,将得到 0 -1 .当您将 -1 重新解释为 uchar 时,会得到 255 .

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.

您可以使用以下条件将该表达式转换为Java:

You can convert this expression to Java with a conditional:

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

由于分支,它不会像原始分支那样快.但是,由于Java缺乏将布尔值重新解释为数字的功能,因此您几乎无能为力.

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.

这篇关于一元减号运算符如何在C ++中对布尔值进行运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆