Why use bitwise operators?

So, I am now learning C ++ through the book "SAMS learn C ++ for 1 hour per day." So far this is great - I understood everything I said, and I managed to use all of them in simple programs to practice them.

However, I just got into the Pobitovo operations section, and I'm completely at a dead end. I understand that you have &, ~, |, <<, → etc., and I understand that each of them performs a different action on the number in its binary form, since ~ flips the numbers.

The problem is that I just cannot understand how and why you want to use them. I’m very happy that I have to take an int, flip the binary digits and have another number, but how exactly does this help me to form or shape in any way? I would appreciate an explanation of why you will use each of them, and, if possible, an example?

Thanks everyone!

+4
source share
1 answer

There are many applications, but here are two examples. Suppose you have eight single-bit values ​​stored in a single-byte container. Bitwise - and with a power of two, it will be easy to access individual bits.

If you scan high intensity pixels in an RGB image, you can use bitwise - and with 128 against three color values; which is a faster operation than another boolean expression such as R> 128.

+1
source

Source: https://habr.com/ru/post/1479990/


All Articles