# Laboratory: C's Bitwise Operations

Summary: In today's lab, you will explore C's bitwise operations and the applications of those operations.

Contents:

## Exercises

### Exercise 1: Setting Selected Bits

Kernighan and Ritchi claim that

```x &= ~077;
```

sets the last six bits of x to zero.

a. Explain their claim.

b. Write a program that helps you verify that claim.

c. Explain how to set the last six bits of x to one. You may want to verify your answer with a variant of your program from step b.

d. Explain how to set the last seven bits of x to zero. You may want to verify your answer with a variant of your program from step b.

e. Explain how to set the last seven bits of x to one. You may want to verify your answer with a variant of your program from step b.

f. Explain how to set the last five bits of x to zero. You may want to verify your answer with a variant of your program from step b.

g. Explain how to set the last five bits of x to one. You may want to verify your answer with a variant of your program from step b.

Read the manual page for the Unix/Linux `open` system call. How would one use bitwise operations in calls to this procedure?

### Exercise 3: Printing Binary Representations

Write a procedure, `void printBits(int i)`, that prints the bits in `i`.

### Exercise 4: Right Shift

Kernighan and Ritchie note that

Right shifting a signed quantity will fill with sign bits (arithmetic shfit) on some machines and with 0-bits (logical shift) on others.

a. Determine what happens on our machines.

b. Determine what happens in Java.

### Exercise 5: Rotating Binary Representations

a. Write a function, `int rightrot(int x, int n)`, that returns the value of the integer `x` rotated to the right by `n` bit positions. (This exercise is essentially the same as Exercise 2-8 of Kernighan and Ritchie.)

b. How or why might you use `rightrot`?

>

## History

Tuesday, 11 February 2003 [Samuel A. Rebelsky]

• Created.

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Fri May 2 14:19:42 2003.
The source to the document was last modified on Tue Feb 11 14:06:29 2003.
This document may be found at `http://www.cs.grinnell.edu/~rebelsky/Courses/CS195/2003S/Labs/bits.html`.

You may wish to validate this document's HTML ; ; Check with Bobby

Samuel A. Rebelsky, rebelsky@grinnell.edu