Previous page Select page Next page

Shifting things around

Let's now think about how we could get some buttons pegged to the centre of the screen - vertically, horizontally or both. How would we do it? Let's take the example of putting at button at the top centre of the window. The "top" value is easy - we just place it at 0 + pegBorder, as we have seen, but what about the "left" value? We would:

  1. Get the width of the client area of the window.
  2. Get the width of the button.
  3. Subtract value 2 from value 1.
  4. Divide the result by 2.

Well, none of that is difficult, except for the "divide by 2" bit. That we don't know how to do. If you've been doing a bit of research, you might have noticed that there are MUL and a DIV mnemonics for "multiply" and "divide", respectively, and "yes" you could use the latter to divide by 2. But there is a much easier way (and much faster). Let's look at a decimal number line holding the value 256. You can see that there are 6 units, 5 tens and 2 hundreds, making 256.

What would happen if we "shifted" the numbers one place to the left? The "2" would now be in the thousands box, the "5" would be in the hundreds and the "6" would now be in the tens. That would leave "0" in the units, giving us the situation below:

We now have the number 2,560. We have multiplied it by 10 because 10 is the number base.

What would happen if we shifted everything one place to the right? Firstly, we'd lose the "6" but we can catch it in a "register" (the same happens if we shift something to the left and there is a number in the leftmost "box") and everything else would be divided by a value equal to the number base.

Of course, we don't have to shift things just one place to the right or left. We can shift any number of places in either direction. What would be the effect of shifting 256 three places to the left? Yes, we would multiply it by 103, or 1,000.

The SHR and SHL mnemonics

In assembler, we perform these shifts by means of the SHR and SHL instructions - right and left, respectively. However, because the number base is not 10 but 2, each place we shift the numbers multiplies or divides them by 2. That means if we want to divide, say, the contents of Ebx by 2, we would say:


    SHR Ebx, 1

And that's all there is to it. In a later chapter, we'll take a look at multiplying and dividing by numbers other than 2 but for now that's all we need to get moving on our learning.

Previous page Select page Next page