Programming in C

(Barry) #1

292 Chapter 12 Operations on Bits


bfffc448
abcdef00
def00abc

The function first ensures that the shift count,n, is valid.The code
if ( n > 0 )
n = n % 32;
else
n = -(-n % 32);
checks first to see if nis positive. If it is, the value of nmodulo the size of an int
(assumed to be 32 in this example) is calculated and stored back inside n.This places the
shift count in the range of 0 through 31. If nis negative, its value is negated before the
modulus operator is applied.This is done because C does not define the sign of the
result of applying the modulus operator to a negative value.Your machine can produce
either a positive or negative result. By negating the value first, you ensure the result is
positive.You then apply the unary minus operator to the result to turn it negative again;
that is, within the range of values –31 through 0.
If the adjusted shift count is 0, the function simply assigns valueto result.
Otherwise, it proceeds with the rotation.
An n-bit rotation to the left is divided into three steps by the function. First, the n
leftmost bits of valueare extracted and shifted to the right.This is done by shifting
valueto the right by the size of an int(in our case, 32) minus n. Next,valueis shifted
nbits to the left, and finally, the extracted bits are ORed back in. A similar procedure is
followed to rotate valueto the right.
In the mainroutine, note the use of hexadecimal notation for a change.The first call
to the rotatefunction specifies that the value of w1is to be rotated eight bits to the left.
As can be seen from the program’s output, the hexadecimal value cdef00ab is returned
by the rotatefunction, which is in fact abcdef00 rotated to the left eight bits.
The second call to the rotatefunction has the effect of rotating the value of w1 16
bits to the right.
The next two calls to the rotatefunction do similar things with the value of w2and
are fairly self-explanatory.The next-to-last call to rotatespecifies a rotate count of 0.
The program’s output verifies that in such a case the function simply returns the value
unchanged.
The final call to rotatespecifies a left rotate 44 places.This has the net effect of
rotating the value left 12 bits (44 % 32 is 12).

Bit Fields


With the bit operators discussed previously, you can proceed to perform all sorts of
sophisticated operations on bits. Bit operations are frequently performed on data items

Program 12.4 Continued
Free download pdf