20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Bit Operators<br />

289<br />

Program 12.3 Cont<strong>in</strong>ued<br />

unsigned <strong>in</strong>t shift (unsigned <strong>in</strong>t value, <strong>in</strong>t n)<br />

{<br />

if ( n > 0 ) // left shift<br />

value = -n;<br />

}<br />

return value;<br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

unsigned <strong>in</strong>t w1 = 0177777u, w2 = 0444u;<br />

unsigned <strong>in</strong>t shift (unsigned <strong>in</strong>t value, <strong>in</strong>t n);<br />

pr<strong>in</strong>tf ("%o\t%o\n", shift (w1, 5), w1 > 6);<br />

pr<strong>in</strong>tf ("%o\t%o\n", shift (w2, 0), w2 >> 0);<br />

pr<strong>in</strong>tf ("%o\n", shift (shift (w1, -3), 3));<br />

}<br />

return 0;<br />

Program 12.3 Output<br />

7777740 7777740<br />

1777 1777<br />

444 444<br />

177770<br />

The shift function shown <strong>in</strong> Program 12.3 declares the type of the argument value to<br />

be unsigned <strong>in</strong>t, thus ensur<strong>in</strong>g that a right shift of value will be zero filled; <strong>in</strong> other<br />

words, performed as a logical right shift.<br />

If the value of n, which is the shift count, is greater than zero, the function shifts<br />

value left n bits. If n is negative (or zero), the function performs a right shift, where the<br />

number of places that value is shifted is obta<strong>in</strong>ed by negat<strong>in</strong>g the value of n.<br />

The first call to the shift function from the ma<strong>in</strong> rout<strong>in</strong>e specifies that the value of<br />

w1 is to be left shifted five bits.The pr<strong>in</strong>tf call that displays the result of the call to the<br />

shift function also displays the result of directly shift<strong>in</strong>g w1 left five places so that these<br />

values can be compared.<br />

The second call to the shift function has the effect of shift<strong>in</strong>g w1 six places to the<br />

right.The result returned by the function is identical to the result obta<strong>in</strong>ed by directly<br />

shift<strong>in</strong>g w1 to the right six places, as verified by the program’s output.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!