Sunday, July 31, 2011

C++ Bits Operators

A bit related operation allows you to control how values are stored in bits. This is not an operation you will need to perform very often, especially not in the early stages of your C++ journey. Nevertheless, bit operations (and related overloaded operators) are present on all GUI or application programming environments, so much that you should be aware of what they do or what they offer. At this time, you should (must) be aware of what a bit, byte, and a word are.
Bits Operators: The Bitwise NOT Operator
 One of the operations you can perform on a bit consists of reversing its value. That is, if a bit holds a value of 1, you may want to change it to 0 and vice-versa. This operation can be taken care of by the bitwise NOT operator that is represented with the tilde symbol ~
The bitwise NOT is a unary operator that must be placed on the left side of its operand as in

 To perform this operation, the compiler considers each bit that is part of the operand and inverts the value of each bit from 1 to 0 or from 0 to 1 depending on the value the bit is holding. This operation can be resumed in the following table:

Bit ~Bit
1 0
0 1
 Consider a number with a byte value such as 248. In our study of numeric systems, we define how to convert numbers from one system to another (this could be a good time to review or study the numeric systems). Based on this, the binary value of decimal 248 is 1111 1000 (and its hexadecimal value is 0xF8). If you apply the bitwise NOT operator on it to reverse the values of its bits, you would get the following result:

 Value 1 1 1 1 1 0 0 0
~Value 0 0 0 0 0 1 1 1


via [functionx]

0 comments:

Post a Comment