Bit Operators 289
unsigned int shift (unsigned int value, int n)
{
if ( n > 0 ) // left shift
value <<= n;
else // right shift
value >>= -n;
return value;
}
int main (void)
{
unsigned int w1 = 0177777u, w2 = 0444u;
unsigned int shift (unsigned int value, int n);
printf ("%o\t%o\n", shift (w1, 5), w1 << 5);
printf ("%o\t%o\n", shift (w1, -6), w1 >> 6);
printf ("%o\t%o\n", shift (w2, 0), w2 >> 0);
printf ("%o\n", shift (shift (w1, -3), 3));
return 0;
}
Program 12.3 Output
7777740 7777740
1777 1777
444 444
177770
The shiftfunction shown in Program 12.3 declares the type of the argument valueto
be unsigned int, thus ensuring that a right shift of valuewill be zero filled; in other
words, performed as a logical right shift.
If the value of n, which is the shift count, is greater than zero, the function shifts
valueleft nbits. If nis negative (or zero), the function performs a right shift, where the
number of places that valueis shifted is obtained by negating the value of n.
The first call to the shiftfunction from the mainroutine specifies that the value of
w1is to be left shifted five bits.The printfcall that displays the result of the call to the
shiftfunction also displays the result of directly shifting w1left five places so that these
values can be compared.
The second call to the shiftfunction has the effect of shifting w1six places to the
right.The result returned by the function is identical to the result obtained by directly
shifting w1to the right six places, as verified by the program’s output.
Program 12.3 Continued