6

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!

Noth
  • 63
  • 1
  • 2
  • 6

1 Answers1

1

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.

Bennett Brown
  • 5,234
  • 1
  • 27
  • 35