Game Development Reference
In-Depth Information
Table 3-4. The Result of Using Bitwise ^ on 0x0F and 0x18
128
64
32
16
8
4
2
1
first
0
0
0
0
1
1
1
1
second
0
0
0
1
1
0
0
0
xord
0
0
0
1
0
1
1
1
The result from 0x0F ^ 0x18 is 0x17. As you can see, every column that contains a 1 and a 0 resulted
in a 1 being placed into the result. The columns that contain two 1s or two 2s all result in 0s being
stored.
The Left Shift (<<) Operator
You can use the left shift operator to move bits to the left by a specified number of bits. The following
code shows how we can use the shift operator.
unsigned int shifted = 1 << 1;
If you print the value stored in shifted you will see that it contains the number 2. This is because the
bit to the left of the first bit represents 2. The following patterns show what has happened.
128
64
32
16
8
4
2
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
1
0
If we had shifted the number of bits by 2 then shifted would have contained 4. When we use the
left shift operator, all of the bits at the right of the pattern are set to 0. This ensures that we do not
introduce new values into our variable.
A more complicated way of thinking about the shift operator is to imagine that we are multiplying the
left value by 2 raised to the power of the number of shifted bits. In our example, we had 1*(2^1)=2.
If we had shifted by 4 bits we would have 1*2^4=16.
The last thing you should consider when using left shift is what happens to values on the end.
Consider the following line of code.
unsigned int shifted = 0x80000000 << 1;
This code shows that we will shift the end bit off of the end. In this case shifted will store 0 after
execution. As all bits to the right of the shift are set to 0, any bits that are shifted out of the variable
will be lost.
 
 
Search WWH ::




Custom Search