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!
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 .
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.
In C++, bitwise operators perform operations on integer data at the individual bit-level. These operations include testing, setting, or shifting the actual bits.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With