288 Chapter 12 Operations on Bits
high-order bits.What is shifted in on the left for signed values depends on the sign of
the value that is being shifted and also on how this operation is implemented on your
computer system. If the sign bit is 0 (meaning the value is positive), 0 s are shifted in
regardless of which machine you are running. However, if the sign bit is 1 , on some
machines 1 s are shifted in, and on others 0 s are shifted in.This former type of operation
is known as an arithmeticright shift, whereas the latter is known as a logicalright shift.
Never make any assumptions about whether a system implements an arithmetic or a
logical right shift. A program that shifts signed values right might work correctly on one
system but fail on another due to this type of assumption.
If w1is an unsigned int, which is represented in 32 bits, and w1is set equal to hexa-
decimal F777EE22, then shifting w1one place to the right with the statement
w1 >>= 1;
sets w1equal to hexadecimal 7BBBF711.
w1 1111 0111 0111 0111 1110 1110 0010 0010 F777EE22
w1 >> 1 0111 1011 1011 1011 1111 0111 0001 0001 7BBBF711
If w1were declared to be a (signed) int, the same result would be produced on some
computers; on others, the result would be FBBBF711 if the operation were performed as
an arithmetic right shift.
It should be noted that the C language does not produce a defined result if an
attempt is made to shift a value to the left or right by an amount that is greater than or
equal to the number of bits in the size of the data item. So, on a machine that represents
integers in 32 bits, for example, shifting an integer to the left or right by 32 or more bits
is not guaranteed to produce a defined result in your program.You should also note that
if you shift a value by a negative amount, the result is also undefined.
A Shift Function
Now, it’s time to put the left and right shift operators to work in an actual program
example, as shown in Program 12.3. Some computers have a single machine instruction
to shift a value to the left if the shift count is positive and to the right if the shift count
is negative. Now, write a function in C to mimic this type of operation.You can have the
function take two arguments: the value to be shifted and the shift count. If the shift
count is positive, the value is shifted left the designated number of places; otherwise, the
value is shifted right the number of places as specified by the absolute value of the shift
count.
Program 12.3 Implementing a Shift Function
// Function to shift an unsigned int left if
// the count is positive, and right if negative
#include <stdio.h>