Explain, please, what are the bitwise operators and what is the principle of their work? I have reread the chapter of K & R several times and read it online, but I don’t understand them.
If possible, with practical examples.
Thank you for understanding.
The principle of operation is extremely simple: we are working with bits of integers. There is, for example, the number 10, it will be 1010 in binary, so if it is int (4 bytes, 32 bits), then it will be:
0000 0000 . 0000 0000 . 0000 0000 . 0000 1010
There is, for example, the number 7. It will be equal to:
0000 0000 . 0000 0000 . 0000 0000 . 0000 0111
You can produce a conjunction of 7 & 10, i.e. put these numbers on top of each other and carry out the conjunction of each bit of one number with the corresponding bit of another number. Will be:
0000 0000 . 0000 0000 . 0000 0000 . 0000 0010
The same logic with "or", i.e. '|' and with "addition modulo 2", i.e. "^".
In the internet a lot of information, of course. You can read more about the shift (bitwise shift).
Used in combinatorics, there are many examples, for example, in the algorithm for generating the set of all subsets (using both "shift" and "bitwise and").
Or maybe it will also be interesting to understand: binary algorithm for finding the GCD of two numbers
As the name suggests, they change / check one or more bits in the machine representation of whole binary (long long, long, int, short, char) numbers.
For example, for int x;
if (x & 1) // нечетное х = (х+7) & ~7; // сделаем его ближайшим большим кратным 8
To understand these operations, it is necessary to understand the representation of numbers in machine memory in the bit representation. After that, you yourself will figure out how and when to apply them.
It is quite common to use them for manipulating bitmaps, where individual bits are tightly packed into an array of bytes (or words). For example, an array for 8,000,000 bits will occupy 1,000,000 bytes of memory.