问题描述
如何使用按位运算符表示条件运算符?
How is the conditional operator represented using bitwise operators?
这是一个作业问题,在这里我必须仅使用按位运算来实现条件运算符.如果允许使用if
语句会很简单,但是必须严格按位进行运算.
It is a homework question where I have to implement the conditional operator using only bitwise operations. It would be simple if if
statements were allowed, however it has to be strictly bitwise operators.
只能使用运算符!
,~
,&
,^
,|
,+
,>>
和<<
.不能使用if
语句或循环.
Only the operators !
, ~
, &
, ^
, |
, +
, >>
, and <<
can be used. No if
statements or loops can be used.
该函数采用三个整数,并且与普通的条件运算符一样工作.第一个参数的值为零或非零.如果第一个参数为零,则返回第二个参数.如果第一个参数不为零,则返回第三个参数.
The function takes three ints and works just like the normal conditional operator. The first argument is evaluated as either zero or non-zero. If the first argument is zero then the second argument is returned. If the first argument is non-zero then the third argument is returned.
我希望对此有一个简单的算法.关于从哪里开始的任何想法都会有很大的帮助.
I was hoping there would be a simple algorithm for this. Any ideas on where to start would be a great help.
推荐答案
是否允许将移位作为按位运算符?可以使用算术运算符吗?
Are shifts allowed as bitwise operators? Are arithmetic operators allowed?
您的修改尚不完全清楚,但是我认为您需要实现等效的
Your edit is not entirely clear, but I assume that you need to implement an equivalent of
a ? b : c
其中a
,b
和c
是整数.反过来等同于
where a
, b
and c
are integers. This is in turn equivalent to
a != 0 ? b : c
一种实现方法是找到一种仅使用按位运算符将a
的非零值转换为全1的位模式的方法.如果我们弄清楚该怎么做,其余的将很容易.现在,我不会立即记住任何能做到这一点的巧妙技巧(我相信它们确实存在),而且我不确定是否允许哪些运算符,所以现在我将只使用类似
One way to achieve that is to find a way to turn non-zero value of a
into an all-ones bit pattern using only bitwise operators. If we figure out how to do that, the rest would be easy. Now, I don't immediately remember any ingenious tricks that would do that (they do exist I believe), and I don't know for sure which operators are allowed and which are not, so for now I will just use something like
a |= a >> 1; a |= a >> 2; a |= a >> 4; a |= a >> 8; a |= a >> 16;
a |= a << 1; a |= a << 2; a |= a << 4; a |= a << 8; a |= a << 16;
对于32位整数类型,如果(且仅当)原始a
中至少设置了一位,以上内容应导致a
的所有位均设置为1.(假设我们正在使用无符号整数,以避免与有符号值移位相关的问题.再次,我敢肯定,必须有一种更聪明的方法来做到这一点.例如:a = !a - 1
,但是我不知道是否允许!
和-
.
For a 32-bit integer type, if (and only if) there was at least one bit set in the original a
, the above should result in all bits of a
set to 1. (Let's assume we are working with unsigned integers, to avoid the issues associated with shifting of signed values). Again, there must be a more clever way to do that, I'm sure. For example: a = !a - 1
, but I don't know if !
and -
are allowed.
完成此操作后,原始条件运算符将等效于
Once we've done that, the original conditional operator becomes equivalent to
(a & b) | (~a & c)
完成.
这篇关于有条件的使用按位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!