Why do we need bitwise operators and what do they actually do in C?

Hello!
Please explain why bitwise operators are needed and what is the principle of their operation? I've already reread the K&R chapter several times and read it online, but I don't understand them.
If possible, with practical examples.
Thanks for understanding.

Author: Grundy, 2012-04-14

3 answers

The principle of operation is extremely simple: we work with bits of integers. There is, for example, the number 10, it will be 1010 in binary, so if it is an int (4 bytes, 32 bits), then it will be:

0000 0000 . 0000 0000 . 0000 0000 . 0000 1010

There is also, for example, the number 7. It will be equal to:

0000 0000 . 0000 0000 . 0000 0000 . 0000 0111

You can make a conjunction of 7 & 10, i.e. put these numbers on top of each other and make a 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 (both "shift" and "bitwise and" are used).

Or maybe it will also be interesting to understand: binary algorithm for finding the node of two numbers

 7
Author: ivkremer, 2012-04-14 16:49:09

As the name suggests, they modify/check one or several bits in the machine representation of binary integers (long long, long, int, short, char).

For example, for int x;

if (x & 1) // нечетное
    х = (х+7) & ~7; // сделаем его ближайшим большим кратным 8

, etc.

To understand these operations, requires understanding of the representation of numbers in machine memory in bit representation. After that, you will figure out how and when to use them.

It is very common to use them for manipulating bitmaps. arrays, where individual bits are tightly packed into an array of bytes (or words). For example, an array for 8000000 bits will take up 1000000 bytes of memory.

 3
Author: avp, 2012-04-14 17:28:17
 0
Author: VioLet, 2017-04-12 07:33:14