使用按位运算符的条件语句 [英] Conditional Statement using Bitwise operators

查看:199
本文介绍了使用按位运算符的条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我看到已经提出了这个问题,但是答案有些模糊且无济于事.好的,我只需要使用& ^〜!+ | >><<"

So I see that this question has already been asked, however the answers were a little vague and unhelpful. Okay, I need to implement a c expression using only "& ^ ~ ! + | >> <<"

表达式需要类似于:a? b:c

The expression needs to resemble: a ? b : c

因此,据我所知,表达式需要看起来像这样:

So, from what I've been able to tell, the expression needs to look something like:

return (a & b) | (~a & c)

这在a = 0时起作用,因为将其与b取和将得到零,然后or表达式将返回右侧,(~a & c)起作用,因为〜0给出全为1,而将所有c都与和c则返回c

This works when a = 0, because anding it with b will give zero, and then the or expression will return the right side, (~a & c) which works because ~0 gives all ones, and anding c with all ones returns c.

但是,当>> 0时,此功能将无效.有人可以尝试解释它的原因或解决方法吗?

However, this doesn't work when a > 0. Can someone try to explain why this is, or how to fix it?

推荐答案

我将使用!!aa转换为布尔值,以获取0或1.x = !!a.

I would convert a to a boolean using !!a, to get 0 or 1. x = !!a.

然后我将其取二.由于没有可用的一元减号,因此可以使用2的补数求反的定义:反转位,然后加一个:y = ~x + 1.这样将清除所有位或设置所有位.

Then I'd negate that in two's complement. Since you don't have unary minus available, you use the definition of 2's complement negation: invert the bits, then add one: y = ~x + 1. That will give either all bits clear, or all bits set.

然后我将直接使用一个变量y & b与另一个变量~y & c取反的and.这将为其中一个表达式赋予0,为另一个表达式赋予原始变量.当我们将它们全部or在一起时,零将无效,因此我们将获得原始变量,不变.

Then I'd and that directly with one variable y & b, its inverse with the other: ~y & c. That will give a 0 for one of the expressions, and the original variable for the other. When we or those together, the zero will have no effect, so we'll get the original variable, unchanged.

这篇关于使用按位运算符的条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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