B Imp= C
This is the same as B = B
Table 6.2: Shortcut Bitwise Operators
The SHL and SHR Operators
SHL stands for shift left and SHR stands for shift right. As the names imply, these
operators shift the bits of a byte or integer-type variable either left or right. The following
table shows the syntax diagram of both operators.
SHL (Shift bits left)
B = variable SHL
Shifts the bits of variable left number of
SHR (Shift bits right)
B = variable SHR
Shifts the bits of variable right number of
Table 6.3: SHL and SHR Operators
Shifting left is the same as multiplying by 2 and shifting right is the same as
dividing by 2. You can see this by looking at the binary representation of a number. Take
the byte value of 1 which is 0000 0001. The 1 is in the 2
equals 1. Shifting
the bit left, makes 0000 0010, putting the 1 bit in the 2
position, which evaluates to 2.
This is the same as 1*2. Shifting left again puts the bit at the 2
position, 0000 0100
which evaluates to 4, or 2 *2. Shifting the bit right puts the 1 back in the 2
0000 0010, which evaluates to 2, or 4/2. Shifting right again puts the 1 bit in the 2
position, 0000 0001, which is 1 or 2/2.
The shift operation can be used as a replacement for multiplication or division if
you are working with powers of 2, but it is primarily used to pack data items into
variables, or to retrieve data items from variables. You saw this demonstrated in the
MAKDWORD macro which was defined as
In this macro, the value of x is converted to an integer, and then shifted left 16 bits
into the high word. An integer is 4 bytes and can be represented as 00000000 00000000
00000000 00000001 . Shifting 16 bits left makes 00000000 00000001 00000000
00000000. Remember that a word is two bytes, so the 1 has been shifted to the high
word of the integer. You can then use the Hiword function to retrieve this value.
The following program shows the SHL and SHR operators.