Programming in C

(Barry) #1

290 Chapter 12 Operations on Bits


In the third call to shift,a shift count of zero is specified. In this case, the shift func-
tion performs a right shift of value by zero bits, which, as you can see from the program’s
output, has no effect on the value.
The final printfcall illustrates nested function calls to the shiftfunction.The
innermost call to shiftis executed first.This call specifies that w1is to be shifted right
three places.The result of this function call, which is 0017777 , is then passed to the
shiftfunction to be shifted to the left three places. As you can see from the program’s
output, this has the net effect of setting the low-order three bits of w1to 0 .(Of course,
you know by now that this could also have been done by simply ANDing w1with ~7.)

Rotating Bits


For the next program example, which ties together some of the bit operations presented
in this chapter, you will develop a function to rotate a value to the left or right.The
process of rotation is similar to shifting, except that when a value is rotated to the left,
the bits that are shifted out of the high-order bits are shifted back into the low-order
bits.When a value is rotated to the right, the bits that are shifted out of the low-order
bits of the value are shifted back into the high-order bits. So, if you are dealing with 32-
bit unsigned integers, the value hexadecimal 80000000 rotated to the left by one bit pro-
duces hexadecimal 00000001 because the 1 from the sign bit that is normally lost by a
left shift of one bit is brought around and shifted back into the low-order bit.
Your function takes two arguments: the first, the value to be rotated, and the second,
the number of bits by which the object is to be rotated. If this second argument is posi-
tive, you rotate the value to the left; otherwise, you rotate the value to the right.
You can adopt a fairly straightforward approach to implementing your rotate func-
tion. For example, to compute the result of rotating xto the left by nbits, where xis of
type intand nranges from 0 to the number of bits in an intminus 1, you can extract
the leftmost nbits of x, shift xto the left by nbits, and then put the extracted bits back
into xat the right. A similar algorithm also can be used to implement the right rotate
function.
Program 12.4 implements the rotatefunction using the algorithm described previ-
ously.This function makes the assumption that an intuses 32 bits on the computer.
Exercises at the end of the chapter show one way to write this function so that this
assumption does not have to be made.

Program 12.4 Implementing a Rotate Function
// Program to illustrate rotation of integers

#include <stdio.h>

int main (void)
{
unsigned int w1 = 0xabcdef00u, w2 = 0xffff1122u;
unsigned int rotate (unsigned int value, int n);
Free download pdf