Jan
Jan

Reputation: 43199

Bitwise operators in Python

not a native programmer here (medical background). I am looking for a bitwise operator that gives me the following results given the following conditions. The programming language is Python but that should not be too relevant:

condition1 condition2 result
0          1          0
1          1          1
1          0          1
0          0          1

Is this achievable with one operator alone? How would the code look like? I know it can be achieved with if/else statements but am interested in understanding new fields of programming.

Upvotes: 1

Views: 644

Answers (3)

khelwood
khelwood

Reputation: 59232

Your expected result is 1 for every case except the first.

The first case (where condition1 is 0 and condition2 is 1) is described by ~condition1 & condition2.

The opposite of that expression is

condition1 | ~condition2

so this expression gives the expected result for every case.


As requested, some detail on the difference between logical boolean operations and bitwise operations.

If we have two boolean values A and B, and we want to perform an "or" operation on them, we use the Python operator or and we get back one boolean value.

If we have two integers A and B, and we want to perform a bitwise "or" operation on them, we use the Python operator | and we get back an int whose bits are determined by the operation's action on each bit in A and B.

For instance

If A is 12 and B is 5, then they have the following bits:

A   = 1100
B   = 0101
A|B = 1101

In this case, the result A|B is 1101 binary, which is 13 decimal.

With the bitwise "not" operator the result is a little more complex to understand.

The binary representation of the number 1 is that the smallest bit is 1 and all the other bits are zero. So when you perform ~1, you don't get zero. You get a number whose every bit is 1 except for the smallest, which is zero.

 1 = 00...001
~1 = 11...110

Because ints are stored in two's complement, 11...110 is the binary representation of the number -2.

So though the boolean not operator gives you not 1==0 (i.e. not True==False), the bitwise ~ operator gives you ~1 == -2, since every individual bit gets flipped.

Upvotes: 3

Superior
Superior

Reputation: 885

this is clearly not (not A and B)
usind De Morgan A or not B
In bitwise meaning A | ~B

| is or, ~ is invert (not)

Upvotes: 1

abc
abc

Reputation: 11949

You could use condition1**condition2

>>> 0**1
0
>>> 1**1
1
>>> 1**0
1
>>> 0**0
1

or more generally condition1 OR (NOT condition2)

Upvotes: 1

Related Questions