Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use Bitwise operators? [duplicate]

Tags:

c++

So I'm currently in the process of learning C++ via the book 'SAMS teach yourself C++ in 1 hour a day'. So far it's been great - I've understood everything that's said and I have managed to use all of them in simple programs to practice them.

However I just got to the section on the Bitwise operators and I am completely stumped. I understand that you have &, ~, |, <<, >> etc, and I understand that each one performs a different action upon a number in its binary form, for ~ flips the numbers over.

The problem I have is that I just can't get my head around how and why you'd want to use them. It's all very well me being to take an int, flip the binary digits over and have another number, but how exactly does this help me in any way shape or form? I'd appreciate an explanation as to why you'd use each one, and if possible maybe an example?

Thanks everyone!

like image 603
Noth Avatar asked May 09 '13 20:05

Noth


People also ask

What are the advantages of using bitwise operations?

Bitwise operations are incredibly simple and thus usually faster than arithmetic operations. For example to get the green portion of an rgb value, the arithmetic approach is (rgb / 256) % 256 . With bitwise operations you would do something as (rgb >> 8) & 0xFF .

What is the purpose of bitwise operators?

A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits. Bitwise operators are used in: Communication stacks where the individual bits in the header attached to the data signify important information.

Why we use bitwise operators in C++?

In C++, bitwise operators perform operations on integer data at the individual bit-level. These operations include testing, setting, or shifting the actual bits.


1 Answers

There are a lot of applications, but here are two examples. Suppose you have eight one-bit values stored in a one-byte container. Bitwise-and with a power of two will access individual bits easily.

If you're scanning for high intensity pixels in an RGB image, you can use bitwise-and with 128 against the three color values; that's a faster operation than another Boolean expression like R>128.

like image 180
Bennett Brown Avatar answered Oct 27 '22 00:10

Bennett Brown