Don't understand Python bit operations & |

I don't understand what bit operations do with a number like & and |

5 & 3 gives 1, and 5 | 3 gives 7. I thought it selects the smallest\largest respectively and subtracts\adds the difference. But 8 & 5 outputs 0, not 3, according to my guess; 3 | 6 outputs 7, not 9.

Please help me figure it out. I read it on the Internet-it's complicated and confusing. If the answer to the question about the bit is NOT ~ I got the answer that

The bitwise operation NOT for the number x corresponds to -(x+1) so that ~5 gives -6.

And here everything is immediately clear, then on bit and and OR there is no clear answer in simple words.

Author: MaxU, 2018-08-17

2 answers

For the difference, there is a subtraction operation :) You would do well to first understand what bits are. Read a little bit about the binary system.

In a nutshell, according to your questions. 5 represent as 101 and 3 as 011 (here we are talking about the representation of decimal numbers in the binary system), the bitwise и leaves one only when both values in the corresponding digit are units

101
&
011
___
001

As you can see here, the unit remains where the two units in the two numbers being compared (represented in the binary system of calculus)

The second example will also be considered. | - bitwise или . "Leaves" units when any of the corresponding digits of numbers is a unit. I.e.

101
|
011
___
111

And 111 this is 7 in the decimal system.

That's actually all.

Here's a straight-up jump for you to read about bit operations https://server.179.ru/tasks/python/2014b1/22-bits.html - the first link in the google. Here is another worthy description https://learn.javascript.ru/bitwise-operators

Well, yes, why would you need it? Well that's a different question altogether :)

 3
Author: zalex, 2018-08-17 18:26:13

It's pretty simple.

A bitwise "And" is an operation on two bits that outputs one when both its arguments are equal to one: 1 & 1 = 1, 1 & 0 = 0, 0 & 1 = 0, 0 & 0 = 0.

A bitwise " OR " is an operation on two bits that outputs one when one of its arguments is equal to one. If both - too: 1 & 1 = 1, 1 & 0 = 1, 0 & 1 = 1, 0 & 0 = 0.

And now see how, for example, the bitwise "And" is performed for the numbers 5 and 8. First, write them in binary form (one byte is enough for each of them):

00000101

And

00001000

Now let's perform the "And" operation as described above bitwise over the corresponding bits and write the result:

00000000, since only the bits that are set to one in EACH of the arguments are set to one.

The result of the "OR" operation will be 00001101, since the bits set to one in ANY of the arguments.

The XOR operation, by the way, is similar to "OR", but it sets to one those bits whose operands DIFFER.

Ah, yes. The standard use of bit "AND" and "OR" is to check/reset and set the bit fields accordingly. I'll write it in a sish notation, will you understand?

unsigned char bitfield = 0x0a; // decimal 10, binary 00001010
...
bitfield = bitfield | 0x01;// устанавливаем самый правый бит в единицу
if (bitfield & 0x02) {     // проверяем, взведён ли второй справа бит.
...                        // внутренняя логика этой операции проста: в скобках получится не-ноль 
                           // (то есть "истина" в понимании Си) только если в переменной bitfield 
}                          // *тоже* взведён второй бит (остальные на результат не влияют,
                           // т.к. при битовом "И" с 00000010 всё равно обращаются в ноль)
bitfield = bitfield & 0xfe;// сбрасываем самый правый бит в ноль, не трогая 
                           // остальные (0xfe - это 11111110)
 3
Author: Alexander Prokoshev, 2018-08-17 19:03:29